-
Notifications
You must be signed in to change notification settings - Fork 183
/
device_buffer.pyx
487 lines (396 loc) · 15 KB
/
device_buffer.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
# Copyright (c) 2019-2020, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
cimport cython
from cpython.bytes cimport PyBytes_AS_STRING, PyBytes_FromStringAndSize
from cython.operator cimport dereference
from libc.stdint cimport uintptr_t
from libcpp.memory cimport unique_ptr
from libcpp.utility cimport move
from rmm._cuda.stream cimport Stream
from rmm._cuda.stream import DEFAULT_STREAM
cimport cuda.ccudart as ccudart
from cuda.ccudart cimport (
cudaError,
cudaError_t,
cudaMemcpyAsync,
cudaMemcpyKind,
cudaStream_t,
cudaStreamSynchronize,
)
from rmm._lib.memory_resource cimport get_current_device_resource
# The DeviceMemoryResource attribute could be released prematurely
# by the gc if the DeviceBuffer is in a reference cycle. Removing
# the tp_clear function with the no_gc_clear decoration prevents that.
# See https://github.com/rapidsai/rmm/pull/931 for details.
@cython.no_gc_clear
cdef class DeviceBuffer:
def __cinit__(self, *,
uintptr_t ptr=0,
size_t size=0,
Stream stream=DEFAULT_STREAM):
"""Construct a ``DeviceBuffer`` with optional size and data pointer
Parameters
----------
ptr : int
pointer to some data on host or device to copy over
size : int
size of the buffer to allocate
(and possibly size of data to copy)
stream : optional
CUDA stream to use for construction and/or copying,
defaults to the CUDA default stream. A reference to the
stream is stored internally to ensure it doesn't go out of
scope while the DeviceBuffer is in use. Destroying the
underlying stream while the DeviceBuffer is in use will
result in undefined behavior.
Note
----
If the pointer passed is non-null and ``stream`` is the default stream,
it is synchronized after the copy. However if a non-default ``stream``
is provided, this function is fully asynchronous.
Examples
--------
>>> import rmm
>>> db = rmm.DeviceBuffer(size=5)
"""
cdef const void* c_ptr
with nogil:
c_ptr = <const void*>ptr
if size == 0:
self.c_obj.reset(new device_buffer())
elif c_ptr == NULL:
self.c_obj.reset(new device_buffer(size, stream.view()))
else:
self.c_obj.reset(new device_buffer(c_ptr, size, stream.view()))
if stream.c_is_default():
stream.c_synchronize()
# Save a reference to the MR and stream used for allocation
self.mr = get_current_device_resource()
self.stream = stream
def __len__(self):
return self.size
def __sizeof__(self):
return self.size
def __bytes__(self):
return self.tobytes()
@property
def nbytes(self):
return self.size
@property
def ptr(self):
return int(<uintptr_t>self.c_data())
@property
def size(self):
return int(self.c_size())
def __reduce__(self):
return to_device, (self.copy_to_host(),)
@property
def __cuda_array_interface__(self):
cdef dict intf = {
"data": (self.ptr, False),
"shape": (self.size,),
"strides": None,
"typestr": "|u1",
"version": 0
}
return intf
@staticmethod
cdef DeviceBuffer c_from_unique_ptr(unique_ptr[device_buffer] ptr):
cdef DeviceBuffer buf = DeviceBuffer.__new__(DeviceBuffer)
buf.c_obj = move(ptr)
return buf
@staticmethod
cdef DeviceBuffer c_to_device(const unsigned char[::1] b,
Stream stream=DEFAULT_STREAM):
"""Calls ``to_device`` function on arguments provided"""
return to_device(b, stream)
@staticmethod
def to_device(const unsigned char[::1] b,
Stream stream=DEFAULT_STREAM):
"""Calls ``to_device`` function on arguments provided"""
return to_device(b, stream)
cpdef copy_to_host(self, ary=None, Stream stream=DEFAULT_STREAM):
"""Copy from a ``DeviceBuffer`` to a buffer on host
Parameters
----------
hb : ``bytes``-like buffer to write into
stream : CUDA stream to use for copying, default the default stream
Examples
--------
>>> import rmm
>>> db = rmm.DeviceBuffer.to_device(b"abc")
>>> hb = bytearray(db.nbytes)
>>> db.copy_to_host(hb)
>>> print(hb)
bytearray(b'abc')
>>> hb = db.copy_to_host()
>>> print(hb)
bytearray(b'abc')
"""
cdef const device_buffer* dbp = self.c_obj.get()
cdef size_t s = dbp.size()
cdef unsigned char[::1] hb = ary
if hb is None:
# NumPy leverages huge pages under-the-hood,
# which speeds up the copy from device to host.
hb = ary = np.empty((s,), dtype="u1")
elif len(hb) < s:
raise ValueError(
"Argument `hb` is too small. Need space for %i bytes." % s
)
copy_ptr_to_host(<uintptr_t>dbp.data(), hb[:s], stream)
return ary
cpdef copy_from_host(self, ary, Stream stream=DEFAULT_STREAM):
"""Copy from a buffer on host to ``self``
Parameters
----------
hb : ``bytes``-like buffer to copy from
stream : CUDA stream to use for copying, default the default stream
Examples
--------
>>> import rmm
>>> db = rmm.DeviceBuffer(size=10)
>>> hb = b"abcdef"
>>> db.copy_from_host(hb)
>>> hb = db.copy_to_host()
>>> print(hb)
array([97, 98, 99, 0, 0, 0, 0, 0, 0, 0], dtype=uint8)
"""
cdef device_buffer* dbp = self.c_obj.get()
cdef const unsigned char[::1] hb = ary
cdef size_t s = len(hb)
if s > self.size:
raise ValueError(
"Argument `hb` is too large. Need space for %i bytes." % s
)
copy_host_to_ptr(hb[:s], <uintptr_t>dbp.data(), stream)
cpdef copy_from_device(self, cuda_ary,
Stream stream=DEFAULT_STREAM):
"""Copy from a buffer on host to ``self``
Parameters
----------
cuda_ary : object to copy from that has ``__cuda_array_interface__``
stream : CUDA stream to use for copying, default the default stream
Examples
--------
>>> import rmm
>>> db = rmm.DeviceBuffer(size=5)
>>> db2 = rmm.DeviceBuffer.to_device(b"abc")
>>> db.copy_from_device(db2)
>>> hb = db.copy_to_host()
>>> print(hb)
array([97, 98, 99, 0, 0], dtype=uint8)
"""
if not hasattr(cuda_ary, "__cuda_array_interface__"):
raise ValueError(
"Expected object to support `__cuda_array_interface__` "
"protocol"
)
cuda_ary_interface = cuda_ary.__cuda_array_interface__
shape = cuda_ary_interface["shape"]
strides = cuda_ary_interface.get("strides")
dtype = np.dtype(cuda_ary_interface["typestr"])
if len(shape) > 1:
raise ValueError(
"Only 1-D contiguous arrays are supported, got {}-D "
"array".format(str(len(shape)))
)
if strides is not None:
if strides[0] != dtype.itemsize:
raise ValueError(
"Only 1-D contiguous arrays are supported, got a "
"non-contiguous array"
)
cdef uintptr_t src_ptr = cuda_ary_interface["data"][0]
cdef size_t s = shape[0] * dtype.itemsize
if s > self.size:
raise ValueError(
"Argument `hb` is too large. Need space for %i bytes." % s
)
cdef device_buffer* dbp = self.c_obj.get()
copy_device_to_ptr(
<uintptr_t>src_ptr,
<uintptr_t>dbp.data(),
s,
stream
)
cpdef bytes tobytes(self, Stream stream=DEFAULT_STREAM):
cdef const device_buffer* dbp = self.c_obj.get()
cdef size_t s = dbp.size()
cdef bytes b = PyBytes_FromStringAndSize(NULL, s)
cdef unsigned char* p = <unsigned char*>PyBytes_AS_STRING(b)
cdef unsigned char[::1] mv = (<unsigned char[:(s + 1):1]>p)[:s]
self.copy_to_host(mv, stream)
return b
cdef size_t c_size(self) except *:
return self.c_obj.get()[0].size()
cpdef void reserve(self,
size_t new_capacity,
Stream stream=DEFAULT_STREAM) except *:
self.c_obj.get()[0].reserve(new_capacity, stream.view())
cpdef void resize(self,
size_t new_size,
Stream stream=DEFAULT_STREAM) except *:
self.c_obj.get()[0].resize(new_size, stream.view())
cpdef size_t capacity(self) except *:
return self.c_obj.get()[0].capacity()
cdef void* c_data(self) except *:
return self.c_obj.get()[0].data()
cdef device_buffer c_release(self) except *:
"""
Releases ownership the data held by this DeviceBuffer.
"""
return move(cython.operator.dereference(self.c_obj))
@cython.boundscheck(False)
cpdef DeviceBuffer to_device(const unsigned char[::1] b,
Stream stream=DEFAULT_STREAM):
"""Return a new ``DeviceBuffer`` with a copy of the data
Parameters
----------
b : ``bytes``-like data on host to copy to device
stream : CUDA stream to use for copying, default the default stream
Returns
-------
``DeviceBuffer`` with copy of data from host
Examples
--------
>>> import rmm
>>> db = rmm._lib.device_buffer.to_device(b"abc")
>>> print(bytes(db))
b'abc'
"""
if b is None:
raise TypeError(
"Argument 'b' has incorrect type"
" (expected bytes-like, got NoneType)"
)
cdef uintptr_t p = <uintptr_t>&b[0]
cdef size_t s = len(b)
return DeviceBuffer(ptr=p, size=s, stream=stream)
@cython.boundscheck(False)
cdef void _copy_async(const void* src,
void* dst,
size_t count,
ccudart.cudaMemcpyKind kind,
cuda_stream_view stream) nogil except *:
"""
Asynchronously copy data between host and/or device pointers
This is a convenience wrapper around cudaMemcpyAsync that
checks for errors. Only used for internal implementation.
Parameters
----------
src : pointer to ``bytes``-like host buffer to or device data to copy from
dst : pointer to ``bytes``-like host buffer to or device data to copy into
count : the size in bytes to copy
stream : CUDA stream to use for copying, default the default stream
"""
cdef cudaError_t err = cudaMemcpyAsync(dst, src, count, kind,
<cudaStream_t>stream)
if err != cudaError.cudaSuccess:
raise RuntimeError(f"Memcpy failed with error: {err}")
@cython.boundscheck(False)
cpdef void copy_ptr_to_host(uintptr_t db,
unsigned char[::1] hb,
Stream stream=DEFAULT_STREAM) except *:
"""Copy from a device pointer to a buffer on host
Parameters
----------
db : pointer to data on device to copy
hb : ``bytes``-like buffer to write into
stream : CUDA stream to use for copying, default the default stream
Note
----
If ``stream`` is the default stream, it is synchronized after the copy.
However if a non-default ``stream`` is provided, this function is fully
asynchronous.
Examples
--------
>>> import rmm
>>> db = rmm.DeviceBuffer.to_device(b"abc")
>>> hb = bytearray(db.nbytes)
>>> rmm._lib.device_buffer.copy_ptr_to_host(db.ptr, hb)
>>> print(hb)
bytearray(b'abc')
"""
if hb is None:
raise TypeError(
"Argument `hb` has incorrect type"
" (expected bytes-like, got NoneType)"
)
with nogil:
_copy_async(<const void*>db, <void*>&hb[0], len(hb),
cudaMemcpyKind.cudaMemcpyDeviceToHost, stream.view())
if stream.c_is_default():
stream.c_synchronize()
@cython.boundscheck(False)
cpdef void copy_host_to_ptr(const unsigned char[::1] hb,
uintptr_t db,
Stream stream=DEFAULT_STREAM) except *:
"""Copy from a host pointer to a device pointer
Parameters
----------
hb : ``bytes``-like host buffer to copy
db : pointer to data on device to write into
stream : CUDA stream to use for copying, default the default stream
Note
----
If ``stream`` is the default stream, it is synchronized after the copy.
However if a non-default ``stream`` is provided, this function is fully
asynchronous.
Examples
--------
>>> import rmm
>>> db = rmm.DeviceBuffer(size=10)
>>> hb = b"abc"
>>> rmm._lib.device_buffer.copy_host_to_ptr(hb, db.ptr)
>>> hb = db.copy_to_host()
>>> print(hb)
array([97, 98, 99, 0, 0, 0, 0, 0, 0, 0], dtype=uint8)
"""
if hb is None:
raise TypeError(
"Argument `hb` has incorrect type"
" (expected bytes-like, got NoneType)"
)
with nogil:
_copy_async(<const void*>&hb[0], <void*>db, len(hb),
cudaMemcpyKind.cudaMemcpyHostToDevice, stream.view())
if stream.c_is_default():
stream.c_synchronize()
@cython.boundscheck(False)
cpdef void copy_device_to_ptr(uintptr_t d_src,
uintptr_t d_dst,
size_t count,
Stream stream=DEFAULT_STREAM) except *:
"""Copy from a device pointer to a device pointer
Parameters
----------
d_src : pointer to data on device to copy from
d_dst : pointer to data on device to write into
stream : CUDA stream to use for copying, default the default stream
Examples
--------
>>> import rmm
>>> import numpy as np
>>> db = rmm.DeviceBuffer(size=5)
>>> db2 = rmm.DeviceBuffer.to_device(b"abc")
>>> rmm._lib.device_buffer.copy_device_to_ptr(db2.ptr, db.ptr, db2.size)
>>> hb = db.copy_to_host()
>>> print(hb)
array([10, 11, 12, 0, 0], dtype=uint8)
"""
with nogil:
_copy_async(<const void*>d_src, <void*>d_dst, count,
cudaMemcpyKind.cudaMemcpyDeviceToDevice, stream.view())