Skip to content
This repository was archived by the owner on Nov 17, 2023. It is now read-only.

Commit 7735a2b

Browse files
committed
allow mixed types in array func protocol
1 parent d6c3578 commit 7735a2b

File tree

2 files changed

+22
-10
lines changed

2 files changed

+22
-10
lines changed

python/mxnet/numpy/multiarray.py

+16-10
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
from ..context import current_context
4949
from ..ndarray import numpy as _mx_nd_np
5050
from ..ndarray.numpy import _internal as _npi
51-
from ..ndarray.ndarray import _storage_type, from_numpy
51+
from ..ndarray.ndarray import _storage_type
5252
from .utils import _get_np_op
5353
from .fallback import * # pylint: disable=wildcard-import,unused-wildcard-import
5454
from . import fallback
@@ -148,10 +148,10 @@ def _reshape_view(a, *shape): # pylint: disable=redefined-outer-name
148148

149149
def _as_mx_np_array(object, ctx=None):
150150
"""Convert object to mxnet.numpy.ndarray."""
151-
if isinstance(object, _np.ndarray):
152-
if not object.flags['C_CONTIGUOUS']:
153-
object = _np.ascontiguousarray(object, dtype=object.dtype)
154-
ret = from_numpy(object, array_cls=ndarray)
151+
if isinstance(object, ndarray):
152+
return object
153+
elif isinstance(object, _np.ndarray):
154+
ret = array(object, dtype=object.dtype, ctx=ctx)
155155
return ret if ctx is None else ret.as_in_ctx(ctx=ctx)
156156
elif isinstance(object, (integer_types, numeric_types)):
157157
return object
@@ -358,11 +358,17 @@ def __array_function__(self, func, types, args, kwargs): # pylint: disable=bad-
358358
out = func(*new_args, **new_kwargs)
359359
return _as_mx_np_array(out, ctx=cur_ctx)
360360
else:
361-
# Note: this allows subclasses that don't override
362-
# __array_function__ to handle mxnet.numpy.ndarray objects
363-
if not py_all(issubclass(t, ndarray) for t in types):
364-
return NotImplemented
365-
return mx_np_func(*args, **kwargs)
361+
if py_all(issubclass(t, ndarray) for t in types):
362+
return mx_np_func(*args, **kwargs)
363+
else:
364+
try:
365+
cur_ctx = next(a.ctx for a in args if hasattr(a, 'ctx'))
366+
except StopIteration:
367+
cur_ctx = next(a.ctx for a in kwargs.values() if hasattr(a, 'ctx'))
368+
new_args = _as_mx_np_array(args, ctx=cur_ctx)
369+
new_kwargs = {k: _as_mx_np_array(v, cur_ctx) for k, v in kwargs.items()}
370+
return mx_np_func(*new_args, **new_kwargs)
371+
366372

367373
def _get_np_basic_indexing(self, key):
368374
"""

tests/python/unittest/test_numpy_ndarray.py

+6
Original file line numberDiff line numberDiff line change
@@ -1369,3 +1369,9 @@ def test_dlpack(dtype, size):
13691369
same(a_np+1, b)
13701370
same(a_np+2, c)
13711371
same(a_np+2, a_copy)
1372+
1373+
@use_np
1374+
def test_mixed_array_types():
1375+
np_array = _np.array([[1, 2], [3, 4], [5, 6]], dtype="float32")
1376+
mx_array = mx.np.ones((3, 1))
1377+
assert_almost_equal(mx_array + np_array, 1+np_array)

0 commit comments

Comments
 (0)