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
|
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define _MULTIARRAYMODULE
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "dlpack/dlpack.h"
#include "numpy/arrayobject.h"
#include "npy_argparse.h"
#include "npy_dlpack.h"
static void
array_dlpack_deleter(DLManagedTensor *self)
{
/*
* Leak the pyobj if not initialized. This can happen if we are running
* exit handlers that are destructing c++ objects with residual (owned)
* PyObjects stored in them after the Python runtime has already been
* terminated.
*/
if (!Py_IsInitialized()) {
return;
}
PyGILState_STATE state = PyGILState_Ensure();
PyArrayObject *array = (PyArrayObject *)self->manager_ctx;
// This will also free the shape and strides as it's one allocation.
PyMem_Free(self);
Py_XDECREF(array);
PyGILState_Release(state);
}
/* This is exactly as mandated by dlpack */
static void dlpack_capsule_deleter(PyObject *self) {
if (PyCapsule_IsValid(self, NPY_DLPACK_USED_CAPSULE_NAME)) {
return;
}
/* an exception may be in-flight, we must save it in case we create another one */
PyObject *type, *value, *traceback;
PyErr_Fetch(&type, &value, &traceback);
DLManagedTensor *managed =
(DLManagedTensor *)PyCapsule_GetPointer(self, NPY_DLPACK_CAPSULE_NAME);
if (managed == NULL) {
PyErr_WriteUnraisable(self);
goto done;
}
/*
* the spec says the deleter can be NULL if there is no way for the caller
* to provide a reasonable destructor.
*/
if (managed->deleter) {
managed->deleter(managed);
/* TODO: is the deleter allowed to set a python exception? */
assert(!PyErr_Occurred());
}
done:
PyErr_Restore(type, value, traceback);
}
/* used internally, almost identical to dlpack_capsule_deleter() */
static void array_dlpack_internal_capsule_deleter(PyObject *self)
{
/* an exception may be in-flight, we must save it in case we create another one */
PyObject *type, *value, *traceback;
PyErr_Fetch(&type, &value, &traceback);
DLManagedTensor *managed =
(DLManagedTensor *)PyCapsule_GetPointer(self, NPY_DLPACK_INTERNAL_CAPSULE_NAME);
if (managed == NULL) {
PyErr_WriteUnraisable(self);
goto done;
}
/*
* the spec says the deleter can be NULL if there is no way for the caller
* to provide a reasonable destructor.
*/
if (managed->deleter) {
managed->deleter(managed);
/* TODO: is the deleter allowed to set a python exception? */
assert(!PyErr_Occurred());
}
done:
PyErr_Restore(type, value, traceback);
}
// This function cannot return NULL, but it can fail,
// So call PyErr_Occurred to check if it failed after
// calling it.
static DLDevice
array_get_dl_device(PyArrayObject *self) {
DLDevice ret;
ret.device_type = kDLCPU;
ret.device_id = 0;
PyObject *base = PyArray_BASE(self);
// walk the bases (see gh-20340)
while (base != NULL && PyArray_Check(base)) {
base = PyArray_BASE((PyArrayObject *)base);
}
// The outer if is due to the fact that NumPy arrays are on the CPU
// by default (if not created from DLPack).
if (PyCapsule_IsValid(base, NPY_DLPACK_INTERNAL_CAPSULE_NAME)) {
DLManagedTensor *managed = PyCapsule_GetPointer(
base, NPY_DLPACK_INTERNAL_CAPSULE_NAME);
if (managed == NULL) {
return ret;
}
return managed->dl_tensor.device;
}
return ret;
}
PyObject *
array_dlpack(PyArrayObject *self,
PyObject *const *args, Py_ssize_t len_args, PyObject *kwnames)
{
PyObject *stream = Py_None;
NPY_PREPARE_ARGPARSER;
if (npy_parse_arguments("__dlpack__", args, len_args, kwnames,
"$stream", NULL, &stream, NULL, NULL, NULL)) {
return NULL;
}
if (stream != Py_None) {
PyErr_SetString(PyExc_RuntimeError,
"NumPy only supports stream=None.");
return NULL;
}
if ( !(PyArray_FLAGS(self) & NPY_ARRAY_WRITEABLE)) {
PyErr_SetString(PyExc_BufferError,
"Cannot export readonly array since signalling readonly "
"is unsupported by DLPack.");
return NULL;
}
npy_intp itemsize = PyArray_ITEMSIZE(self);
int ndim = PyArray_NDIM(self);
npy_intp *strides = PyArray_STRIDES(self);
npy_intp *shape = PyArray_SHAPE(self);
if (!PyArray_IS_C_CONTIGUOUS(self) && PyArray_SIZE(self) != 1) {
for (int i = 0; i < ndim; ++i) {
if (shape[i] != 1 && strides[i] % itemsize != 0) {
PyErr_SetString(PyExc_BufferError,
"DLPack only supports strides which are a multiple of "
"itemsize.");
return NULL;
}
}
}
DLDataType managed_dtype;
PyArray_Descr *dtype = PyArray_DESCR(self);
if (PyDataType_ISBYTESWAPPED(dtype)) {
PyErr_SetString(PyExc_BufferError,
"DLPack only supports native byte order.");
return NULL;
}
managed_dtype.bits = 8 * itemsize;
managed_dtype.lanes = 1;
if (PyDataType_ISBOOL(dtype)) {
managed_dtype.code = kDLBool;
}
else if (PyDataType_ISSIGNED(dtype)) {
managed_dtype.code = kDLInt;
}
else if (PyDataType_ISUNSIGNED(dtype)) {
managed_dtype.code = kDLUInt;
}
else if (PyDataType_ISFLOAT(dtype)) {
// We can't be sure that the dtype is
// IEEE or padded.
if (itemsize > 8) {
PyErr_SetString(PyExc_BufferError,
"DLPack only supports IEEE floating point types "
"without padding (longdouble typically is not IEEE).");
return NULL;
}
managed_dtype.code = kDLFloat;
}
else if (PyDataType_ISCOMPLEX(dtype)) {
// We can't be sure that the dtype is
// IEEE or padded.
if (itemsize > 16) {
PyErr_SetString(PyExc_BufferError,
"DLPack only supports IEEE floating point types "
"without padding (longdouble typically is not IEEE).");
return NULL;
}
managed_dtype.code = kDLComplex;
}
else {
PyErr_SetString(PyExc_BufferError,
"DLPack only supports signed/unsigned integers, float "
"and complex dtypes.");
return NULL;
}
DLDevice device = array_get_dl_device(self);
if (PyErr_Occurred()) {
return NULL;
}
// ensure alignment
int offset = sizeof(DLManagedTensor) % sizeof(void *);
void *ptr = PyMem_Malloc(sizeof(DLManagedTensor) + offset +
(sizeof(int64_t) * ndim * 2));
if (ptr == NULL) {
PyErr_NoMemory();
return NULL;
}
DLManagedTensor *managed = ptr;
/*
* Note: the `dlpack.h` header suggests/standardizes that `data` must be
* 256-byte aligned. We ignore this intentionally, because `__dlpack__`
* standardizes that `byte_offset` must be 0 (for now) to not break pytorch:
* https://github.com/data-apis/array-api/issues/293#issuecomment-964111413
*
* We further assume that exporting fully unaligned data is OK even without
* `byte_offset` since the standard does not reject it.
* Presumably, pytorch will support importing `byte_offset != 0` and NumPy
* can choose to use it starting about 2023. At that point, it may be
* that NumPy MUST use `byte_offset` to adhere to the standard (as
* specified in the header)!
*/
managed->dl_tensor.data = PyArray_DATA(self);
managed->dl_tensor.byte_offset = 0;
managed->dl_tensor.device = device;
managed->dl_tensor.dtype = managed_dtype;
int64_t *managed_shape_strides = (int64_t *)((char *)ptr +
sizeof(DLManagedTensor) + offset);
int64_t *managed_shape = managed_shape_strides;
int64_t *managed_strides = managed_shape_strides + ndim;
for (int i = 0; i < ndim; ++i) {
managed_shape[i] = shape[i];
// Strides in DLPack are items; in NumPy are bytes.
managed_strides[i] = strides[i] / itemsize;
}
managed->dl_tensor.ndim = ndim;
managed->dl_tensor.shape = managed_shape;
managed->dl_tensor.strides = NULL;
if (PyArray_SIZE(self) != 1 && !PyArray_IS_C_CONTIGUOUS(self)) {
managed->dl_tensor.strides = managed_strides;
}
managed->dl_tensor.byte_offset = 0;
managed->manager_ctx = self;
managed->deleter = array_dlpack_deleter;
PyObject *capsule = PyCapsule_New(managed, NPY_DLPACK_CAPSULE_NAME,
dlpack_capsule_deleter);
if (capsule == NULL) {
PyMem_Free(ptr);
return NULL;
}
// the capsule holds a reference
Py_INCREF(self);
return capsule;
}
PyObject *
array_dlpack_device(PyArrayObject *self, PyObject *NPY_UNUSED(args))
{
DLDevice device = array_get_dl_device(self);
if (PyErr_Occurred()) {
return NULL;
}
return Py_BuildValue("ii", device.device_type, device.device_id);
}
NPY_NO_EXPORT PyObject *
from_dlpack(PyObject *NPY_UNUSED(self), PyObject *obj) {
PyObject *capsule = PyObject_CallMethod((PyObject *)obj->ob_type,
"__dlpack__", "O", obj);
if (capsule == NULL) {
return NULL;
}
DLManagedTensor *managed =
(DLManagedTensor *)PyCapsule_GetPointer(capsule,
NPY_DLPACK_CAPSULE_NAME);
if (managed == NULL) {
Py_DECREF(capsule);
return NULL;
}
const int ndim = managed->dl_tensor.ndim;
if (ndim > NPY_MAXDIMS) {
PyErr_SetString(PyExc_RuntimeError,
"maxdims of DLPack tensor is higher than the supported "
"maxdims.");
Py_DECREF(capsule);
return NULL;
}
DLDeviceType device_type = managed->dl_tensor.device.device_type;
if (device_type != kDLCPU &&
device_type != kDLCUDAHost &&
device_type != kDLROCMHost &&
device_type != kDLCUDAManaged) {
PyErr_SetString(PyExc_RuntimeError,
"Unsupported device in DLTensor.");
Py_DECREF(capsule);
return NULL;
}
if (managed->dl_tensor.dtype.lanes != 1) {
PyErr_SetString(PyExc_RuntimeError,
"Unsupported lanes in DLTensor dtype.");
Py_DECREF(capsule);
return NULL;
}
int typenum = -1;
const uint8_t bits = managed->dl_tensor.dtype.bits;
const npy_intp itemsize = bits / 8;
switch (managed->dl_tensor.dtype.code) {
case kDLBool:
if (bits == 8) {
typenum = NPY_BOOL;
}
break;
case kDLInt:
switch (bits)
{
case 8: typenum = NPY_INT8; break;
case 16: typenum = NPY_INT16; break;
case 32: typenum = NPY_INT32; break;
case 64: typenum = NPY_INT64; break;
}
break;
case kDLUInt:
switch (bits)
{
case 8: typenum = NPY_UINT8; break;
case 16: typenum = NPY_UINT16; break;
case 32: typenum = NPY_UINT32; break;
case 64: typenum = NPY_UINT64; break;
}
break;
case kDLFloat:
switch (bits)
{
case 16: typenum = NPY_FLOAT16; break;
case 32: typenum = NPY_FLOAT32; break;
case 64: typenum = NPY_FLOAT64; break;
}
break;
case kDLComplex:
switch (bits)
{
case 64: typenum = NPY_COMPLEX64; break;
case 128: typenum = NPY_COMPLEX128; break;
}
break;
}
if (typenum == -1) {
PyErr_SetString(PyExc_RuntimeError,
"Unsupported dtype in DLTensor.");
Py_DECREF(capsule);
return NULL;
}
npy_intp shape[NPY_MAXDIMS];
npy_intp strides[NPY_MAXDIMS];
for (int i = 0; i < ndim; ++i) {
shape[i] = managed->dl_tensor.shape[i];
// DLPack has elements as stride units, NumPy has bytes.
if (managed->dl_tensor.strides != NULL) {
strides[i] = managed->dl_tensor.strides[i] * itemsize;
}
}
char *data = (char *)managed->dl_tensor.data +
managed->dl_tensor.byte_offset;
PyArray_Descr *descr = PyArray_DescrFromType(typenum);
if (descr == NULL) {
Py_DECREF(capsule);
return NULL;
}
PyObject *ret = PyArray_NewFromDescr(&PyArray_Type, descr, ndim, shape,
managed->dl_tensor.strides != NULL ? strides : NULL, data, 0, NULL);
if (ret == NULL) {
Py_DECREF(capsule);
return NULL;
}
PyObject *new_capsule = PyCapsule_New(managed,
NPY_DLPACK_INTERNAL_CAPSULE_NAME,
array_dlpack_internal_capsule_deleter);
if (new_capsule == NULL) {
Py_DECREF(capsule);
Py_DECREF(ret);
return NULL;
}
if (PyArray_SetBaseObject((PyArrayObject *)ret, new_capsule) < 0) {
Py_DECREF(capsule);
Py_DECREF(ret);
return NULL;
}
if (PyCapsule_SetName(capsule, NPY_DLPACK_USED_CAPSULE_NAME) < 0) {
Py_DECREF(capsule);
Py_DECREF(ret);
return NULL;
}
Py_DECREF(capsule);
return ret;
}
|