Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for __array_interface__ #1071

Merged
merged 8 commits into from
Jul 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 28 additions & 13 deletions dace/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,34 @@ def create_datadescriptor(obj, no_custom_desc=False):
return obj.__descriptor__()
elif not no_custom_desc and hasattr(obj, 'descriptor'):
return obj.descriptor
elif isinstance(obj, (list, tuple, numpy.ndarray)):
if isinstance(obj, (list, tuple)): # Lists and tuples are cast to numpy
obj = numpy.array(obj)
elif dtypes.is_array(obj):
if dtypes.is_gpu_array(obj):
interface = obj.__cuda_array_interface__
storage = dtypes.StorageType.GPU_Global
else:
interface = obj.__array_interface__
storage = dtypes.StorageType.Default

if hasattr(obj, 'dtype') and obj.dtype.fields is not None: # Struct
dtype = dtypes.struct('unnamed', **{k: dtypes.typeclass(v[0].type) for k, v in obj.dtype.fields.items()})
else:
if numpy.dtype(interface['typestr']).type is numpy.void: # Struct from __array_interface__
if 'descr' in interface:
dtype = dtypes.struct('unnamed', **{k: dtypes.typeclass(numpy.dtype(v).type) for k, v in interface['descr']})
else:
raise TypeError(f'Cannot infer data type of array interface object "{interface}"')
else:
dtype = dtypes.typeclass(numpy.dtype(interface['typestr']).type)
itemsize = numpy.dtype(interface['typestr']).itemsize
if len(interface['shape']) == 0:
return Scalar(dtype, storage=storage)
return Array(dtype=dtype,
shape=interface['shape'],
strides=(tuple(s // itemsize for s in interface['strides']) if interface['strides'] else None),
storage=storage)
elif isinstance(obj, (list, tuple)):
# Lists and tuples are cast to numpy
obj = numpy.array(obj)

if obj.dtype.fields is not None: # Struct
dtype = dtypes.struct('unnamed', **{k: dtypes.typeclass(v[0].type) for k, v in obj.dtype.fields.items()})
Expand Down Expand Up @@ -69,16 +94,6 @@ def create_datadescriptor(obj, no_custom_desc=False):
return Array(dtype=TORCH_DTYPE_TO_TYPECLASS[obj.dtype], strides=obj.stride(), shape=tuple(obj.shape))
except ImportError:
raise ValueError("Attempted to convert a torch.Tensor, but torch could not be imported")
elif dtypes.is_gpu_array(obj):
interface = obj.__cuda_array_interface__
dtype = dtypes.typeclass(numpy.dtype(interface['typestr']).type)
itemsize = numpy.dtype(interface['typestr']).itemsize
if len(interface['shape']) == 0:
return Scalar(dtype, storage=dtypes.StorageType.GPU_Global)
return Array(dtype=dtype,
shape=interface['shape'],
strides=(tuple(s // itemsize for s in interface['strides']) if interface['strides'] else None),
storage=dtypes.StorageType.GPU_Global)
elif symbolic.issymbolic(obj):
return Scalar(symbolic.symtype(obj))
elif isinstance(obj, dtypes.typeclass):
Expand Down
6 changes: 4 additions & 2 deletions dace/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1428,10 +1428,12 @@ def is_array(obj: Any) -> bool:
# In PyTorch, accessing this attribute throws a runtime error for
# variables that require grad, or KeyError when a boolean array is used
return True
if hasattr(obj, 'data_ptr') or hasattr(obj, '__array_interface__'):
if hasattr(obj, '__array_interface__'):
return len(obj.__array_interface__['shape']) > 0 # NumPy scalars contain an empty shape tuple
if hasattr(obj, 'data_ptr'):
try:
return hasattr(obj, 'shape') and len(obj.shape) > 0
except TypeError: # NumPy scalar objects define an attribute called shape that cannot be used
except TypeError: # PyTorch scalar objects define an attribute called shape that cannot be used
return False
return False

Expand Down
32 changes: 32 additions & 0 deletions tests/array_interface_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Copyright 2019-2022 ETH Zurich and the DaCe authors. All rights reserved.
import numpy as np

import dace


class ArrayWrapper:
def __init__(self, array, **kwargs):
self.array = array

@property
def __array_interface__(self):
return self.array.__array_interface__


def test_array_interface_input():
@dace.program
def simple_program(A: dace.float64[3, 3, 3]):
A += 1

simple_program.compile()

A = np.ones((3, 3, 3))
Awrap = ArrayWrapper(A)

simple_program(A=Awrap)

np.testing.assert_equal(A, 2)


if __name__ == "__main__":
test_array_interface_input()