-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnpx_numpy_tensors.py
315 lines (278 loc) · 9.76 KB
/
npx_numpy_tensors.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
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
import warnings
from typing import Any, Callable, List, Optional, Tuple
import numpy as np
from onnx import ModelProto, TensorProto
from ..reference import ExtendedReferenceEvaluator
from .._helpers import np_dtype_to_tensor_dtype
from .npx_tensors import EagerTensor, JitTensor
from .npx_types import DType, TensorType
class NumpyTensor:
"""
Default backend based on
:func:`onnx_array_api.reference.ExtendedReferenceEvaluator`.
:param input_names: input names
:param onx: onnx model
"""
class Evaluator:
"""
Wraps class :class:`onnx_array_api.reference.ExtendedReferenceEvaluator`
to have a signature closer to python function.
:param tensor_class: class tensor such as :class:`NumpyTensor`
:param input_names: input names
:param onx: onnx model
:param f: unused except in error messages
"""
def __init__(
self,
tensor_class: type,
input_names: List[str],
onx: ModelProto,
f: Callable,
):
self.ref = ExtendedReferenceEvaluator(onx)
self.input_names = input_names
self.tensor_class = tensor_class
self._f = f
def run(self, *inputs: List["NumpyTensor"]) -> List["NumpyTensor"]:
"""
Executes the function.
:param inputs: function inputs
:return: outputs
"""
if len(inputs) != len(self.input_names):
raise ValueError(
f"Expected {len(self.input_names)} inputs but got {len(inputs)}, "
f"self.input_names={self.input_names}, "
f"inputs={inputs}, f={self._f}."
)
feeds = {}
for name, inp in zip(self.input_names, inputs):
if inp is None:
feeds[name] = None
continue
if not isinstance(inp, (EagerTensor, JitTensor)):
raise TypeError(
f"Unexpected type {type(inp)} for input {name!r}, "
f"inp={inp!r}, f={self._f}."
)
feeds[name] = inp.value
res = self.ref.run(None, feeds)
return list(map(self.tensor_class, res))
def __init__(self, tensor: np.ndarray):
if isinstance(tensor, np.ndarray):
self._tensor = tensor
elif isinstance(tensor, NumpyTensor):
self._tensor = tensor._tensor
elif isinstance(
tensor,
(
np.float16,
np.float32,
np.float64,
np.int64,
np.int32,
np.int16,
np.int8,
np.uint64,
np.uint32,
np.uint16,
np.uint8,
np.bool_,
),
):
self._tensor = np.array(tensor)
else:
raise TypeError(f"A numpy array is expected not {type(tensor)}.")
def __repr__(self) -> str:
"usual"
return f"{self.__class__.__name__}({self._tensor!r})"
def __len__(self):
"usual"
return len(self._tensor)
def numpy(self):
"Returns the array converted into a numpy array."
return self._tensor
@property
def dtype(self) -> DType:
"Returns the element type of this tensor."
return DType(np_dtype_to_tensor_dtype(self._tensor.dtype))
@property
def key(self) -> Any:
"Unique key for a tensor of the same type."
return (self.dtype, len(self._tensor.shape))
@property
def value(self) -> np.ndarray:
"Returns the value of this tensor as a numpy array."
return self._tensor
@property
def tensor_type(self) -> TensorType:
"Returns the tensor type of this tensor."
return TensorType[self.dtype]
@property
def dims(self):
"""
Returns the dimensions of the tensor.
First dimension is the batch dimension if the tensor
has more than one dimension. It is always left undefined.
"""
if len(self._tensor.shape) <= 1:
# a scalar (len==0) or a 1D tensor
return self._tensor.shape
return (None, *tuple(self.shape[1:]))
@property
def ndim(self):
"Returns the number of dimensions (rank)."
return len(self.shape)
@property
def shape(self) -> Tuple[int, ...]:
"Returns the shape of the tensor."
return self._tensor.shape
def tensor_type_dims(self, name: str) -> TensorType:
"""
Returns the tensor type of this tensor.
This property is used to define a key used to cache a jitted function.
Same keys keys means same ONNX graph.
Different keys usually means same ONNX graph but different
input shapes.
:param name: name of the constraint
"""
dt = self.dtype
return TensorType[dt, self.dims, name]
@classmethod
def create_function(
cls: Any, input_names: List[str], onx: ModelProto, f: Callable
) -> Callable:
"""
Creates a python function calling the onnx backend
used by this class.
:param onx: onnx model
:return: python function
"""
return cls.Evaluator(cls, input_names, onx, f=f)
@classmethod
def get_opsets(cls, opsets):
"""
Updates the opsets for a given backend.
This method should be overloaded.
By default, it returns opsets.
"""
return opsets
@classmethod
def get_ir_version(cls, ir_version):
"""
Updates the IR version.
This method should be overloaded.
By default, it returns ir_version.
"""
return ir_version
# The class should support whatever Var supports.
# This part is not yet complete.
class EagerNumpyTensor(NumpyTensor, EagerTensor):
"""
Defines a value for a specific backend.
"""
def __array_namespace__(self, api_version: Optional[str] = None):
"""
Returns the module holding all the available functions.
"""
if api_version is None or api_version == "2022.12":
from onnx_array_api.array_api import onnx_numpy
return onnx_numpy
raise ValueError(
f"Unable to return an implementation for api_version={api_version!r}."
)
def __bool__(self):
"Implicit conversion to bool."
if self.dtype != DType(TensorProto.BOOL):
raise TypeError(
f"Conversion to bool only works for bool scalar, not for {self!r}."
)
if self.shape == (0,):
return False
if self.shape:
warnings.warn(
f"Conversion to bool only works for scalar, not for {self!r}, "
f"bool(...)={bool(self._tensor)}.",
stacklevel=0,
)
try:
return bool(self._tensor)
except ValueError as e:
raise ValueError(f"Unable to convert {self} to bool.") from e
return bool(self._tensor)
def __int__(self):
"Implicit conversion to int."
if self.shape:
raise ValueError(
f"Conversion to bool only works for scalar, not for {self!r}."
)
if self.dtype not in {
DType(TensorProto.INT64),
DType(TensorProto.INT32),
DType(TensorProto.INT16),
DType(TensorProto.INT8),
DType(TensorProto.UINT64),
DType(TensorProto.UINT32),
DType(TensorProto.UINT16),
DType(TensorProto.UINT8),
}:
raise TypeError(
f"Conversion to int only works for int scalar, "
f"not for dtype={self.dtype}."
)
return int(self._tensor)
def __float__(self):
"Implicit conversion to float."
if self.shape:
raise ValueError(
f"Conversion to bool only works for scalar, not for {self!r}."
)
if self.dtype not in {
DType(TensorProto.FLOAT),
DType(TensorProto.DOUBLE),
DType(TensorProto.FLOAT16),
DType(TensorProto.BFLOAT16),
DType(TensorProto.COMPLEX64),
DType(TensorProto.COMPLEX128),
}:
raise TypeError(
f"Conversion to float only works for float scalar, "
f"not for dtype={self.dtype}."
)
return float(self._tensor)
def __complex__(self):
"Implicit conversion to complex."
if self.shape:
raise ValueError(
f"Conversion to bool only works for scalar, not for {self!r}."
)
if self.dtype not in {
DType(TensorProto.FLOAT),
DType(TensorProto.DOUBLE),
DType(TensorProto.FLOAT16),
DType(TensorProto.BFLOAT16),
DType(TensorProto.COMPLEX64),
DType(TensorProto.COMPLEX128),
}:
raise TypeError(
f"Conversion to float only works for float scalar, "
f"not for dtype={self.dtype}."
)
return complex(self._tensor)
def __iter__(self):
"""
The :epkg:`Array API` does not define this function (2022/12).
This method raises an exception with a better error message.
"""
warnings.warn(
f"Iterators are not implemented in the generic case. "
f"Every function using them cannot be converted into ONNX "
f"(tensors - {type(self)}).",
stacklevel=0,
)
for row in self._tensor:
yield self.__class__(row)
class JitNumpyTensor(NumpyTensor, JitTensor):
"""
Defines a value for a specific backend.
"""