forked from apache/mxnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
numpy_dispatch_protocol.py
266 lines (239 loc) · 7.04 KB
/
numpy_dispatch_protocol.py
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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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
#
# https://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.
"""Utils for registering NumPy array function protocol for mxnet.numpy ops."""
from __future__ import absolute_import
import functools
import numpy as _np
from . import numpy as mx_np # pylint: disable=reimported
from .numpy.multiarray import _NUMPY_ARRAY_FUNCTION_DICT, _NUMPY_ARRAY_UFUNC_DICT
def _find_duplicate(strs):
str_set = set()
for s in strs:
if s in str_set:
return s
else:
str_set.add(s)
return None
def _implements(numpy_function):
"""Register an __array_function__ implementation for MyArray objects."""
def decorator(func):
_NUMPY_ARRAY_FUNCTION_DICT[numpy_function] = func
return func
return decorator
def with_array_function_protocol(func):
"""A decorator for functions that expect array function protocol.
The decorated function only runs when NumPy version >= 1.17."""
from distutils.version import LooseVersion
cur_np_ver = LooseVersion(_np.__version__)
np_1_17_ver = LooseVersion('1.17')
@functools.wraps(func)
def _run_with_array_func_proto(*args, **kwargs):
if cur_np_ver >= np_1_17_ver:
try:
func(*args, **kwargs)
except Exception as e:
raise RuntimeError('Running function {} with NumPy array function protocol failed'
' with exception {}'
.format(func.__name__, str(e)))
return _run_with_array_func_proto
def with_array_ufunc_protocol(func):
"""A decorator for functions that expect array ufunc protocol.
The decorated function only runs when NumPy version >= 1.15."""
from distutils.version import LooseVersion
cur_np_ver = LooseVersion(_np.__version__)
np_1_15_ver = LooseVersion('1.15')
@functools.wraps(func)
def _run_with_array_ufunc_proto(*args, **kwargs):
if cur_np_ver >= np_1_15_ver:
try:
func(*args, **kwargs)
except Exception as e:
raise RuntimeError('Running function {} with NumPy array ufunc protocol failed'
' with exception {}'
.format(func.__name__, str(e)))
return _run_with_array_ufunc_proto
_NUMPY_ARRAY_FUNCTION_LIST = [
'argmin',
'argmax',
'around',
'argsort',
'append',
'broadcast_arrays',
'broadcast_to',
'clip',
'concatenate',
'copy',
'cumsum',
'diag',
'diagflat',
'dot',
'expand_dims',
'fix',
'flip',
'inner',
'max',
'mean',
'min',
'nonzero',
'ones_like',
'prod',
'ravel',
'repeat',
'reshape',
'roll',
'split',
'squeeze',
'stack',
'std',
'sum',
'swapaxes',
'take',
'tensordot',
'tile',
'transpose',
'unique',
'unravel_index',
'var',
'vdot',
'vstack',
'column_stack',
'zeros_like',
'linalg.norm',
'linalg.cholesky',
'linalg.inv',
'shape',
'trace',
'tril',
'meshgrid',
'outer',
'einsum',
'shares_memory',
'may_share_memory',
'diff',
'resize',
'where',
]
@with_array_function_protocol
def _register_array_function():
"""Register __array_function__ protocol for mxnet.numpy operators so that
``mxnet.numpy.ndarray`` can be fed into the official NumPy operators and
dispatched to MXNet implementation.
Notes
-----
According the __array_function__ protocol (see the following reference),
there are three kinds of operators that cannot be dispatched using this
protocol:
1. Universal functions, which already have their own protocol in the official
NumPy package.
2. Array creation functions.
3. Dispatch for methods of any kind, e.g., methods on np.random.RandomState objects.
References
----------
https://numpy.org/neps/nep-0018-array-function-protocol.html
"""
dup = _find_duplicate(_NUMPY_ARRAY_FUNCTION_LIST)
if dup is not None:
raise ValueError('Duplicate operator name {} in _NUMPY_ARRAY_FUNCTION_LIST'.format(dup))
for op_name in _NUMPY_ARRAY_FUNCTION_LIST:
strs = op_name.split('.')
if len(strs) == 1:
mx_np_op = getattr(mx_np, op_name)
onp_op = getattr(_np, op_name)
setattr(mx_np, op_name, _implements(onp_op)(mx_np_op))
elif len(strs) == 2:
mx_np_submodule = getattr(mx_np, strs[0])
mx_np_op = getattr(mx_np_submodule, strs[1])
onp_submodule = getattr(_np, strs[0])
onp_op = getattr(onp_submodule, strs[1])
setattr(mx_np_submodule, strs[1], _implements(onp_op)(mx_np_op))
else:
raise ValueError('Does not support registering __array_function__ protocol '
'for operator {}'.format(op_name))
# https://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs
_NUMPY_ARRAY_UFUNC_LIST = [
'abs',
'add',
'arctan2',
'copysign',
'degrees',
'hypot',
'lcm',
# 'ldexp',
'subtract',
'multiply',
'true_divide',
'negative',
'power',
'mod',
'absolute',
'rint',
'sign',
'exp',
'log',
'log2',
'log10',
'expm1',
'sqrt',
'square',
'cbrt',
'reciprocal',
'remainder',
'sin',
'cos',
'tan',
'sinh',
'cosh',
'tanh',
'arcsin',
'arccos',
'arctan',
'arcsinh',
'arccosh',
'arctanh',
'maximum',
'minimum',
'ceil',
'trunc',
'floor',
'bitwise_xor',
'bitwise_or',
'logical_not',
'equal',
'not_equal',
'less',
'less_equal',
'greater',
'greater_equal'
]
@with_array_ufunc_protocol
def _register_array_ufunc():
"""Register NumPy array ufunc protocol.
References
----------
https://numpy.org/neps/nep-0013-ufunc-overrides.html
"""
dup = _find_duplicate(_NUMPY_ARRAY_UFUNC_LIST)
if dup is not None:
raise ValueError('Duplicate operator name {} in _NUMPY_ARRAY_UFUNC_LIST'.format(dup))
for op_name in _NUMPY_ARRAY_UFUNC_LIST:
try:
mx_np_op = getattr(mx_np, op_name)
_NUMPY_ARRAY_UFUNC_DICT[op_name] = mx_np_op
except AttributeError:
raise AttributeError('mxnet.numpy does not have operator named {}'.format(op_name))
_register_array_function()
_register_array_ufunc()