python_code
stringlengths
0
456k
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect from typing import Dict, Sequence, Text, Any class Concat(Base): @staticmethod def export(): # type: () -> None test_cases = { '1d': ([1, 2], [3, 4]), '2d': ([[1, 2], [3, 4]], [[5, 6], [7, 8]]), '3d': ([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[[9, 10], [11, 12]], [[13, 14], [15, 16]]]) } # type: Dict[Text, Sequence[Any]] for test_case, values_ in test_cases.items(): values = [np.asarray(v, dtype=np.float32) for v in values_] for i in range(len(values[0].shape)): in_args = ['value' + str(k) for k in range(len(values))] node = onnx.helper.make_node( 'Concat', inputs=[s for s in in_args], outputs=['output'], axis=i ) output = np.concatenate(values, i) expect(node, inputs=[v for v in values], outputs=[output], name='test_concat_' + test_case + '_axis_' + str(i)) for i in range(-len(values[0].shape), 0): in_args = ['value' + str(k) for k in range(len(values))] node = onnx.helper.make_node( 'Concat', inputs=[s for s in in_args], outputs=['output'], axis=i ) output = np.concatenate(values, i) expect(node, inputs=[v for v in values], outputs=[output], name='test_concat_' + test_case + '_axis_negative_' + str(abs(i)))
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class QuantizeLinear(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node('QuantizeLinear', inputs=['x', 'y_scale', 'y_zero_point'], outputs=['y'],) x = np.array([0, 2, 3, 1000, -254, -1000]).astype(np.float32) y_scale = np.float32(2) y_zero_point = np.uint8(128) y = np.array([128, 129, 130, 255, 1, 0]).astype(np.uint8) expect(node, inputs=[x, y_scale, y_zero_point], outputs=[y], name='test_quantizelinear')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Log(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Log', inputs=['x'], outputs=['y'], ) x = np.array([1, 10]).astype(np.float32) y = np.log(x) # expected output [0., 2.30258512] expect(node, inputs=[x], outputs=[y], name='test_log_example') x = np.exp(np.random.randn(3, 4, 5).astype(np.float32)) y = np.log(x) expect(node, inputs=[x], outputs=[y], name='test_log')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class QLinearMatMul(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node('QLinearMatMul', inputs=['a', 'a_scale', 'a_zero_point', 'b', 'b_scale', 'b_zero_point', 'y_scale', 'y_zero_point'], outputs=['y'],) #2D a = np.array([[208, 236, 0, 238], [3, 214, 255, 29], ], dtype=np.uint8) a_scale = np.array([0.0066], dtype=np.float32) a_zero_point = np.array([113], dtype=np.uint8) b = np.array([[152, 51, 244], [60, 26, 255], [0, 127, 246], [127, 254, 247]], dtype=np.uint8) b_scale = np.array([0.00705], dtype=np.float32) b_zero_point = np.array([114], dtype=np.uint8) y_scale = np.array([0.0107], dtype=np.float32) y_zero_point = np.array([118], dtype=np.uint8) output = np.array([[168, 115, 255], [1, 66, 151], ], dtype=np.uint8) expect(node, inputs=[a, a_scale, a_zero_point, b, b_scale, b_zero_point, y_scale, y_zero_point], outputs=[output], name='test_qlinearmatmul_2D') #3D a = np.array([[[208, 236, 0, 238], [3, 214, 255, 29]], [[208, 236, 0, 238], [3, 214, 255, 29]]], dtype=np.uint8) a_scale = np.array([0.0066], dtype=np.float32) a_zero_point = np.array([113], dtype=np.uint8) b = np.array([[[152, 51, 244], [60, 26, 255], [0, 127, 246], [127, 254, 247]], [[152, 51, 244], [60, 26, 255], [0, 127, 246], [127, 254, 247]]], dtype=np.uint8) b_scale = np.array([0.00705], dtype=np.float32) b_zero_point = np.array([114], dtype=np.uint8) y_scale = np.array([0.0107], dtype=np.float32) y_zero_point = np.array([118], dtype=np.uint8) output = np.array([[[168, 115, 255], [1, 66, 151]], [[168, 115, 255], [1, 66, 151]]], dtype=np.uint8) expect(node, inputs=[a, a_scale, a_zero_point, b, b_scale, b_zero_point, y_scale, y_zero_point], outputs=[output], name='test_qlinearmatmul_3D')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Asin(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Asin', inputs=['x'], outputs=['y'], ) x = np.array([-0.5, 0, 0.5]).astype(np.float32) y = np.arcsin(x) expect(node, inputs=[x], outputs=[y], name='test_asin_example') x = np.random.rand(3, 4, 5).astype(np.float32) y = np.arcsin(x) expect(node, inputs=[x], outputs=[y], name='test_asin')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import math import numpy as np # type: ignore import onnx from ..base import Base from . import expect class LRN(Base): @staticmethod def export(): # type: () -> None alpha = 0.0002 beta = 0.5 bias = 2.0 nsize = 3 node = onnx.helper.make_node( 'LRN', inputs=['x'], outputs=['y'], alpha=alpha, beta=beta, bias=bias, size=nsize ) x = np.random.randn(5, 5, 5, 5).astype(np.float32) square_sum = np.zeros((5, 5, 5, 5)).astype(np.float32) for n, c, h, w in np.ndindex(x.shape): square_sum[n, c, h, w] = sum(x[n, max(0, c - int(math.floor((nsize - 1) / 2))):min(5, c + int(math.ceil((nsize - 1) / 2)) + 1), h, w] ** 2) y = x / ((bias + (alpha / nsize) * square_sum) ** beta) expect(node, inputs=[x], outputs=[y], name='test_lrn') @staticmethod def export_default(): # type: () -> None alpha = 0.0001 beta = 0.75 bias = 1.0 nsize = 3 node = onnx.helper.make_node( 'LRN', inputs=['x'], outputs=['y'], size=3 ) x = np.random.randn(5, 5, 5, 5).astype(np.float32) square_sum = np.zeros((5, 5, 5, 5)).astype(np.float32) for n, c, h, w in np.ndindex(x.shape): square_sum[n, c, h, w] = sum(x[n, max(0, c - int(math.floor((nsize - 1) / 2))):min(5, c + int(math.ceil((nsize - 1) / 2)) + 1), h, w] ** 2) y = x / ((bias + (alpha / nsize) * square_sum) ** beta) expect(node, inputs=[x], outputs=[y], name='test_lrn_default')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect from typing import Tuple, Text def einsum_reference_implementation(Eqn, Operands): # type: (Text, Tuple[np.ndarray, ...]) -> np.ndarray Z = np.einsum(Eqn, *Operands) return Z class Einsum(Base): @staticmethod def export_einsum_transpose(): # type: () -> None Eqn = 'ij->ji' node = onnx.helper.make_node( 'Einsum', inputs=['x'], outputs=['y'], equation=Eqn ) X = np.random.randn(3, 4) Y = einsum_reference_implementation(Eqn, (X,)) expect(node, inputs=[X], outputs=[Y], name='test_einsum_transpose') @staticmethod def export_einsum_sum(): # type: () -> None Eqn = 'ij->i' node = onnx.helper.make_node( 'Einsum', inputs=['x'], outputs=['y'], equation=Eqn ) X = np.random.randn(3, 4) Z = einsum_reference_implementation(Eqn, (X,)) expect(node, inputs=[X], outputs=[Z], name='test_einsum_sum') @staticmethod def export_einsum_batch_diagonal(): # type: () -> None Eqn = '...ii ->...i' node = onnx.helper.make_node( 'Einsum', inputs=['x'], outputs=['y'], equation=Eqn ) X = np.random.randn(3, 5, 5) Z = einsum_reference_implementation(Eqn, (X,)) expect(node, inputs=[X], outputs=[Z], name='test_einsum_batch_diagonal') @staticmethod def export_einsum_inner_prod(): # type: () -> None Eqn = 'i,i' node = onnx.helper.make_node( 'Einsum', inputs=['x', 'y'], outputs=['z'], equation=Eqn ) X = np.random.randn(5) Y = np.random.randn(5) Z = einsum_reference_implementation(Eqn, (X, Y)) expect(node, inputs=[X, Y], outputs=[Z], name='test_einsum_inner_prod') @staticmethod def export_einsum_batch_matmul(): # type: () -> None Eqn = 'bij, bjk -> bik' node = onnx.helper.make_node( 'Einsum', inputs=['x', 'y'], outputs=['z'], equation=Eqn ) X = np.random.randn(5, 2, 3) Y = np.random.randn(5, 3, 4) Z = einsum_reference_implementation(Eqn, (X, Y)) expect(node, inputs=[X, Y], outputs=[Z], name='test_einsum_batch_matmul')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore from typing import Optional import onnx from ..base import Base from . import expect def gemm_reference_implementation(A, B, C=None, alpha=1., beta=1., transA=0, transB=0): # type: (np.ndarray, np.ndarray, Optional[np.ndarray], float, float, int, int) -> np.ndarray A = A if transA == 0 else A.T B = B if transB == 0 else B.T C = C if C is not None else np.array(0) Y = alpha * np.dot(A, B) + beta * C return Y class Gemm(Base): @staticmethod def export_default_zero_bias(): # type: () -> None node = onnx.helper.make_node( 'Gemm', inputs=['a', 'b', 'c'], outputs=['y'] ) a = np.random.ranf([3, 5]).astype(np.float32) b = np.random.ranf([5, 4]).astype(np.float32) c = np.zeros([1, 4]).astype(np.float32) y = gemm_reference_implementation(a, b, c) expect(node, inputs=[a, b, c], outputs=[y], name='test_gemm_default_zero_bias') @staticmethod def export_default_no_bias(): # type: () -> None node = onnx.helper.make_node( 'Gemm', inputs=['a', 'b'], outputs=['y'] ) a = np.random.ranf([2, 10]).astype(np.float32) b = np.random.ranf([10, 3]).astype(np.float32) y = gemm_reference_implementation(a, b) expect(node, inputs=[a, b], outputs=[y], name='test_gemm_default_no_bias') @staticmethod def export_default_scalar_bias(): # type: () -> None node = onnx.helper.make_node( 'Gemm', inputs=['a', 'b', 'c'], outputs=['y'] ) a = np.random.ranf([2, 3]).astype(np.float32) b = np.random.ranf([3, 4]).astype(np.float32) c = np.array(3.14).astype(np.float32) y = gemm_reference_implementation(a, b, c) expect(node, inputs=[a, b, c], outputs=[y], name='test_gemm_default_scalar_bias') @staticmethod def export_default_single_elem_vector_bias(): # type: () -> None node = onnx.helper.make_node( 'Gemm', inputs=['a', 'b', 'c'], outputs=['y'] ) a = np.random.ranf([3, 7]).astype(np.float32) b = np.random.ranf([7, 3]).astype(np.float32) c = np.random.ranf([1]).astype(np.float32) y = gemm_reference_implementation(a, b, c) expect(node, inputs=[a, b, c], outputs=[y], name='test_gemm_default_single_elem_vector_bias') @staticmethod def export_default_vector_bias(): # type: () -> None node = onnx.helper.make_node( 'Gemm', inputs=['a', 'b', 'c'], outputs=['y'] ) a = np.random.ranf([2, 7]).astype(np.float32) b = np.random.ranf([7, 4]).astype(np.float32) c = np.random.ranf([1, 4]).astype(np.float32) y = gemm_reference_implementation(a, b, c) expect(node, inputs=[a, b, c], outputs=[y], name='test_gemm_default_vector_bias') @staticmethod def export_default_matrix_bias(): # type: () -> None node = onnx.helper.make_node( 'Gemm', inputs=['a', 'b', 'c'], outputs=['y'] ) a = np.random.ranf([3, 6]).astype(np.float32) b = np.random.ranf([6, 4]).astype(np.float32) c = np.random.ranf([3, 4]).astype(np.float32) y = gemm_reference_implementation(a, b, c) expect(node, inputs=[a, b, c], outputs=[y], name='test_gemm_default_matrix_bias') @staticmethod def export_transposeA(): # type: () -> None node = onnx.helper.make_node( 'Gemm', inputs=['a', 'b', 'c'], outputs=['y'], transA=1 ) a = np.random.ranf([6, 3]).astype(np.float32) b = np.random.ranf([6, 4]).astype(np.float32) c = np.zeros([1, 4]).astype(np.float32) y = gemm_reference_implementation(a, b, c, transA=1) expect(node, inputs=[a, b, c], outputs=[y], name='test_gemm_transposeA') @staticmethod def export_transposeB(): # type: () -> None node = onnx.helper.make_node( 'Gemm', inputs=['a', 'b', 'c'], outputs=['y'], transB=1 ) a = np.random.ranf([3, 6]).astype(np.float32) b = np.random.ranf([4, 6]).astype(np.float32) c = np.zeros([1, 4]).astype(np.float32) y = gemm_reference_implementation(a, b, c, transB=1) expect(node, inputs=[a, b, c], outputs=[y], name='test_gemm_transposeB') @staticmethod def export_alpha(): # type: () -> None node = onnx.helper.make_node( 'Gemm', inputs=['a', 'b', 'c'], outputs=['y'], alpha=0.5 ) a = np.random.ranf([3, 5]).astype(np.float32) b = np.random.ranf([5, 4]).astype(np.float32) c = np.zeros([1, 4]).astype(np.float32) y = gemm_reference_implementation(a, b, c, alpha=0.5) expect(node, inputs=[a, b, c], outputs=[y], name='test_gemm_alpha') @staticmethod def export_beta(): # type: () -> None node = onnx.helper.make_node( 'Gemm', inputs=['a', 'b', 'c'], outputs=['y'], beta=0.5 ) a = np.random.ranf([2, 7]).astype(np.float32) b = np.random.ranf([7, 4]).astype(np.float32) c = np.random.ranf([1, 4]).astype(np.float32) y = gemm_reference_implementation(a, b, c, beta=0.5) expect(node, inputs=[a, b, c], outputs=[y], name='test_gemm_beta') @staticmethod def export_all_attributes(): # type: () -> None node = onnx.helper.make_node( 'Gemm', inputs=['a', 'b', 'c'], outputs=['y'], alpha=0.25, beta=0.35, transA=1, transB=1 ) a = np.random.ranf([4, 3]).astype(np.float32) b = np.random.ranf([5, 4]).astype(np.float32) c = np.random.ranf([1, 5]).astype(np.float32) y = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35) expect(node, inputs=[a, b, c], outputs=[y], name='test_gemm_all_attributes')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Where(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Where', inputs=['condition', 'x', 'y'], outputs=['z'], ) condition = np.array([[1, 0], [1, 1]], dtype=np.bool) x = np.array([[1, 2], [3, 4]], dtype=np.float32) y = np.array([[9, 8], [7, 6]], dtype=np.float32) z = np.where(condition, x, y) # expected output [[1, 8], [3, 4]] expect(node, inputs=[condition, x, y], outputs=[z], name='test_where_example') @staticmethod def export_long(): # type: () -> None node = onnx.helper.make_node( 'Where', inputs=['condition', 'x', 'y'], outputs=['z'], ) condition = np.array([[1, 0], [1, 1]], dtype=np.bool) x = np.array([[1, 2], [3, 4]], dtype=np.int64) y = np.array([[9, 8], [7, 6]], dtype=np.int64) z = np.where(condition, x, y) # expected output [[1, 8], [3, 4]] expect(node, inputs=[condition, x, y], outputs=[z], name='test_where_long_example')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Cos(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Cos', inputs=['x'], outputs=['y'], ) x = np.array([-1, 0, 1]).astype(np.float32) y = np.cos(x) expect(node, inputs=[x], outputs=[y], name='test_cos_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.cos(x) expect(node, inputs=[x], outputs=[y], name='test_cos')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Or(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Or', inputs=['x', 'y'], outputs=['or'], ) # 2d x = (np.random.randn(3, 4) > 0).astype(np.bool) y = (np.random.randn(3, 4) > 0).astype(np.bool) z = np.logical_or(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_or2d') # 3d x = (np.random.randn(3, 4, 5) > 0).astype(np.bool) y = (np.random.randn(3, 4, 5) > 0).astype(np.bool) z = np.logical_or(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_or3d') # 4d x = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool) y = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool) z = np.logical_or(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_or4d') @staticmethod def export_or_broadcast(): # type: () -> None node = onnx.helper.make_node( 'Or', inputs=['x', 'y'], outputs=['or'], ) # 3d vs 1d x = (np.random.randn(3, 4, 5) > 0).astype(np.bool) y = (np.random.randn(5) > 0).astype(np.bool) z = np.logical_or(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_or_bcast3v1d') # 3d vs 2d x = (np.random.randn(3, 4, 5) > 0).astype(np.bool) y = (np.random.randn(4, 5) > 0).astype(np.bool) z = np.logical_or(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_or_bcast3v2d') # 4d vs 2d x = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool) y = (np.random.randn(5, 6) > 0).astype(np.bool) z = np.logical_or(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_or_bcast4v2d') # 4d vs 3d x = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool) y = (np.random.randn(4, 5, 6) > 0).astype(np.bool) z = np.logical_or(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_or_bcast4v3d') # 4d vs 4d x = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool) y = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool) z = np.logical_or(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_or_bcast4v4d')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect def one_hot(indices, depth, axis=-1, dtype=np.float32): # type: ignore ''' Compute one hot from indices at a specific axis ''' values = np.asarray(indices) rank = len(values.shape) depth_range = np.arange(depth) if axis < 0: axis += (rank + 1) ls = values.shape[0:axis] rs = values.shape[axis:rank] targets = np.reshape(depth_range, (1,) * len(ls) + depth_range.shape + (1,) * len(rs)) values = np.reshape(np.mod(values, depth), ls + (1,) + rs) return np.asarray(targets == values, dtype=dtype) class OneHot(Base): @staticmethod def export_without_axis(): # type: () -> None on_value = 5 off_value = 2 output_type = np.int32 node = onnx.helper.make_node( 'OneHot', inputs=['indices', 'depth', 'values'], outputs=['y'] ) indices = np.array([0, 7, 8], dtype=np.int64) depth = np.float32(12) values = np.array([off_value, on_value], dtype=output_type) y = one_hot(indices, depth, dtype=output_type) y = y * (on_value - off_value) + off_value expect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_without_axis') @staticmethod def export_with_axis(): # type: () -> None axisValue = 1 on_value = 3 off_value = 1 output_type = np.float32 node = onnx.helper.make_node( 'OneHot', inputs=['indices', 'depth', 'values'], outputs=['y'], axis=axisValue ) indices = np.array([[1, 9], [2, 4]], dtype=np.float32) depth = np.array([10], dtype=np.float32) values = np.array([off_value, on_value], dtype=output_type) y = one_hot(indices, depth, axis=axisValue, dtype=output_type) y = y * (on_value - off_value) + off_value expect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_with_axis') @staticmethod def export_with_negative_indices(): # type: () -> None axisValue = 1 on_value = 3 off_value = 1 output_type = np.float32 node = onnx.helper.make_node( 'OneHot', inputs=['indices', 'depth', 'values'], outputs=['y'], axis=axisValue ) indices = np.array([0, -7, -8], dtype=np.int64) depth = np.array([10], dtype=np.float32) values = np.array([off_value, on_value], dtype=output_type) y = one_hot(indices, depth, axis=axisValue, dtype=output_type) y = y * (on_value - off_value) + off_value expect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_negative_indices') # print(y) # [[3. 1. 1. 1. 1. 1. 1. 1. 1. 1.] # [1. 1. 1. 3. 1. 1. 1. 1. 1. 1.] # [1. 1. 3. 1. 1. 1. 1. 1. 1. 1.]] @staticmethod def export_with_negative_axis(): # type: () -> None axisValue = -2 on_value = 3 off_value = 1 output_type = np.float32 node = onnx.helper.make_node( 'OneHot', inputs=['indices', 'depth', 'values'], outputs=['y'], axis=axisValue ) indices = np.array([[1, 9], [2, 4]], dtype=np.float32) depth = np.array([10], dtype=np.float32) values = np.array([off_value, on_value], dtype=output_type) y = one_hot(indices, depth, axis=axisValue, dtype=output_type) y = y * (on_value - off_value) + off_value expect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_with_negative_axis')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect def reshape_reference_implementation(data, shape): # type: (np.ndarray, np.ndarray) -> np.ndarray # replace zeros with corresponding dim size # we need to do this because np.reshape doesn't support 0 new_shape = np.copy(shape) zeros_index = np.where(shape == 0) new_shape[zeros_index] = np.array(data.shape)[zeros_index] reshaped = np.reshape(data, new_shape) return reshaped class Reshape(Base): @staticmethod def export(): # type: () -> None original_shape = [2, 3, 4] test_cases = { 'reordered_all_dims': np.array([4, 2, 3], dtype=np.int64), 'reordered_last_dims': np.array([2, 4, 3], dtype=np.int64), 'reduced_dims': np.array([2, 12], dtype=np.int64), 'extended_dims': np.array([2, 3, 2, 2], dtype=np.int64), 'one_dim': np.array([24], dtype=np.int64), 'negative_dim': np.array([2, -1, 2], dtype=np.int64), 'negative_extended_dims': np.array([-1, 2, 3, 4], dtype=np.int64), 'zero_dim': np.array([2, 0, 4, 1], dtype=np.int64), 'zero_and_negative_dim': np.array([2, 0, 1, -1], dtype=np.int64), } data = np.random.random_sample(original_shape).astype(np.float32) for test_name, shape in test_cases.items(): node = onnx.helper.make_node( 'Reshape', inputs=['data', 'shape'], outputs=['reshaped'], ) reshaped = reshape_reference_implementation(data, shape) expect(node, inputs=[data, shape], outputs=[reshaped], name='test_reshape_' + test_name)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Tan(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Tan', inputs=['x'], outputs=['y'], ) x = np.array([-1, 0, 1]).astype(np.float32) y = np.tan(x) expect(node, inputs=[x], outputs=[y], name='test_tan_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.tan(x) expect(node, inputs=[x], outputs=[y], name='test_tan')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class DequantizeLinear(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node('DequantizeLinear', inputs=['x', 'x_scale', 'x_zero_point'], outputs=['y'],) # scalar zero point and scale x = np.array([0, 3, 128, 255]).astype(np.uint8) x_scale = np.float32(2) x_zero_point = np.uint8(128) y = np.array([-256, -250, 0, 254], dtype=np.float32) expect(node, inputs=[x, x_scale, x_zero_point], outputs=[y], name='test_dequantizelinear')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Unique(Base): @staticmethod def export_sorted_without_axis(): # type: () -> None node_sorted = onnx.helper.make_node( 'Unique', inputs=['X'], outputs=['Y', 'indices', 'inverse_indices', 'counts'] ) x = np.array([2.0, 1.0, 1.0, 3.0, 4.0, 3.0], dtype=np.float32) y, indices, inverse_indices, counts = np.unique(x, True, True, True) expect(node_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_sorted_without_axis') @staticmethod def export_not_sorted_without_axis(): # type: () -> None node_not_sorted = onnx.helper.make_node( 'Unique', inputs=['X'], outputs=['Y', 'indices', 'inverse_indices', 'counts'], sorted=0 ) # numpy unique does not retain original order (it sorts the output unique values) # https://github.com/numpy/numpy/issues/8621 # we need to recover unsorted output and indices x = np.array([2.0, 1.0, 1.0, 3.0, 4.0, 3.0], dtype=np.float32) y, indices, inverse_indices, counts = np.unique(x, True, True, True) # prepare index mapping from sorted to unsorted argsorted_indices = np.argsort(indices) inverse_indices_map = {i: si for i, si in zip(argsorted_indices, np.arange(len(argsorted_indices)))} indices = indices[argsorted_indices] y = np.take(x, indices, axis=0) inverse_indices = np.asarray([inverse_indices_map[i] for i in inverse_indices], dtype=np.int64) counts = counts[argsorted_indices] # print(y) # [2.0, 1.0, 3.0, 4.0] # print(indices) # [0 1 3 4] # print(inverse_indices) # [0, 1, 1, 2, 3, 2] # print(counts) # [1, 2, 2, 1] expect(node_not_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_not_sorted_without_axis') @staticmethod def export_sorted_with_axis(): # type: () -> None node_sorted = onnx.helper.make_node( 'Unique', inputs=['X'], outputs=['Y', 'indices', 'inverse_indices', 'counts'], sorted=1, axis=0 ) x = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]], dtype=np.float32) y, indices, inverse_indices, counts = np.unique(x, True, True, True, axis=0) # print(y) # [[1. 0. 0.] # [2. 3. 4.]] # print(indices) # [0 2] # print(inverse_indices) # [0 0 1] # print(counts) # [2 1] expect(node_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_sorted_with_axis') @staticmethod def export_sorted_with_axis_3d(): # type: () -> None node_sorted = onnx.helper.make_node( 'Unique', inputs=['X'], outputs=['Y', 'indices', 'inverse_indices', 'counts'], sorted=1, axis=1 ) x = np.array([[[1., 1.], [0., 1.], [2., 1.], [0., 1.]], [[1., 1.], [0., 1.], [2., 1.], [0., 1.]]], dtype=np.float32) y, indices, inverse_indices, counts = np.unique(x, True, True, True, axis=1) # print(y) # [[[0. 1.] # [1. 1.] # [2. 1.]] # [[0. 1.] # [1. 1.] # [2. 1.]]] # print(indices) # [1 0 2] # print(inverse_indices) # [1 0 2 0] # print(counts) # [2 1 1] expect(node_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_sorted_with_axis_3d') @staticmethod def export_sorted_with_negative_axis(): # type: () -> None node_sorted = onnx.helper.make_node( 'Unique', inputs=['X'], outputs=['Y', 'indices', 'inverse_indices', 'counts'], sorted=1, axis=-1 ) x = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 3]], dtype=np.float32) y, indices, inverse_indices, counts = np.unique(x, True, True, True, axis=-1) # print(y) # [[0. 1.] # [0. 1.] # [3. 2.]] # print(indices) # [1 0] # print(inverse_indices) # [1 0 0] # print(counts) # [2 1] expect(node_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_sorted_with_negative_axis')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class ReduceMin(Base): @staticmethod def export_do_not_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 0 node = onnx.helper.make_node( 'ReduceMin', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[5., 1.] # [30., 1.] # [55., 1.]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_random') @staticmethod def export_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 1 node = onnx.helper.make_node( 'ReduceMin', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[[5., 1.]] # [[30., 1.]] # [[55., 1.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_random') @staticmethod def export_default_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = None keepdims = 1 node = onnx.helper.make_node( 'ReduceMin', inputs=['data'], outputs=['reduced'], keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1) #print(reduced) #[[[1.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_random') @staticmethod def export_negative_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [-2] keepdims = 1 node = onnx.helper.make_node( 'ReduceMin', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1) # print(reduced) #[[[5., 1.]] # [[30., 1.]] # [[55., 1.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_random')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class ReduceL1(Base): @staticmethod def export_do_not_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [2] keepdims = 0 node = onnx.helper.make_node( 'ReduceL1', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims ) data = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape) #print(data) #[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]] reduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[3., 7.], [11., 15.], [19., 23.]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l1_do_not_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l1_do_not_keepdims_random') @staticmethod def export_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [2] keepdims = 1 node = onnx.helper.make_node( 'ReduceL1', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims ) data = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape) #print(data) #[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]] reduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l1_keep_dims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l1_keep_dims_random') @staticmethod def export_default_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = None keepdims = 1 node = onnx.helper.make_node( 'ReduceL1', inputs=['data'], outputs=['reduced'], keepdims=keepdims ) data = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape) #print(data) #[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]] reduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1) #print(reduced) #[[[78.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l1_default_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l1_default_axes_keepdims_random') @staticmethod def export_negative_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [-1] keepdims = 1 node = onnx.helper.make_node( 'ReduceL1', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims ) data = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape) # print(data) #[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]] reduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1) # print(reduced) #[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l1_negative_axes_keep_dims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l1_negative_axes_keep_dims_random')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class LeakyRelu(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'LeakyRelu', inputs=['x'], outputs=['y'], alpha=0.1 ) x = np.array([-1, 0, 1]).astype(np.float32) # expected output [-0.1, 0., 1.] y = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * 0.1 expect(node, inputs=[x], outputs=[y], name='test_leakyrelu_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * 0.1 expect(node, inputs=[x], outputs=[y], name='test_leakyrelu') @staticmethod def export_leakyrelu_default(): # type: () -> None default_alpha = 0.01 node = onnx.helper.make_node( 'LeakyRelu', inputs=['x'], outputs=['y'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * default_alpha expect(node, inputs=[x], outputs=[y], name='test_leakyrelu_default')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect from onnx.backend.sample.ops.abs import abs class Abs(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Abs', inputs=['x'], outputs=['y'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = abs(x) expect(node, inputs=[x], outputs=[y], name='test_abs')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import sys import re from typing import List, Text, Sequence, Any import numpy as np # type: ignore import onnx import onnx.mapping from ..utils import import_recursive from ..test_case import TestCase _NodeTestCases = [] from onnx.onnx_pb import NodeProto, AttributeProto from onnx.onnx_operators_pb import FunctionProto # FIXME(TMVector): Any reason we can't get rid of this and use the C++ helper directly? def function_expand_helper(node, # type: NodeProto function_proto, # type: FunctionProto op_prefix # type: Text ): # type: (...) -> List[NodeProto] node_list = [] io_names_map = dict() attribute_map = dict((a.name, a) for a in node.attribute) for idx in range(len(function_proto.input)): io_names_map[function_proto.input[idx]] = node.input[idx] \ if idx in range(len(node.input)) else "" for idx in range(len(function_proto.output)): # Even if the node has been created with optional outputs missing, we # can't assume that the function body handles this correctly, such as in # the case that output is also an intermediate value. # So we only add a name mapping if the output is present. An internal # name will be generated if the missing output is used, the same as any # other internal tensor. if idx in range(len(node.output)) and node.output[idx] != "": io_names_map[function_proto.output[idx]] = node.output[idx] for internal_node in function_proto.node: new_node = NodeProto() new_node.CopyFrom(internal_node) new_node.ClearField("input") new_node.ClearField("output") new_node.ClearField("attribute") for internal_name in internal_node.input: if internal_name in io_names_map: new_node.input.append(io_names_map[internal_name]) else: new_node.input.append(op_prefix + internal_name) for internal_name in internal_node.output: if internal_name in io_names_map: new_node.output.append(io_names_map[internal_name]) else: new_node.output.append(op_prefix + internal_name) for attr in internal_node.attribute: if attr.HasField("ref_attr_name"): if attr.ref_attr_name in attribute_map: new_attr = AttributeProto() new_attr.CopyFrom(attribute_map[attr.ref_attr_name]) # type: ignore new_attr.name = attr.name new_node.attribute.extend([new_attr]) else: new_attr = AttributeProto() new_attr.CopyFrom(attr) new_node.attribute.extend([new_attr]) node_list.append(new_node) return node_list def function_testcase_helper(node, name): # type: (NodeProto, Text) -> List[NodeProto] test_op = node.op_type op_prefix = test_op + "_" + name + "_expanded_function" schema = onnx.defs.get_schema(test_op, node.domain) if schema.has_function: # type: ignore function_proto = schema.function_body # type: ignore elif schema.has_context_dependent_function: # type: ignore function_proto_str = schema.get_context_dependent_function(node.SerializeToString()) # type: ignore function_proto = FunctionProto() function_proto.ParseFromString(function_proto_str) else: return [] for attr in schema.attributes: if attr in [a.name for a in node.attribute]: continue if schema.attributes[attr].default_value: node.attribute.extend([schema.attributes[attr].default_value]) # function_proto.attributes node_list = function_expand_helper(node, function_proto, op_prefix) return node_list def _extract_value_info(arr, name): # type: (np.ndarray, Text) -> onnx.ValueInfoProto return onnx.helper.make_tensor_value_info( name=name, elem_type=onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[arr.dtype], shape=arr.shape) def expect(node, # type: onnx.NodeProto inputs, # type: Sequence[np.ndarray] outputs, # type: Sequence[np.ndarray] name, # type: Text **kwargs # type: Any ): # type: (...) -> None present_inputs = [x for x in node.input if (x != '')] present_outputs = [x for x in node.output if (x != '')] inputs_vi = [_extract_value_info(arr, arr_name) for arr, arr_name in zip(inputs, present_inputs)] outputs_vi = [_extract_value_info(arr, arr_name) for arr, arr_name in zip(outputs, present_outputs)] graph = onnx.helper.make_graph( nodes=[node], name=name, inputs=inputs_vi, outputs=outputs_vi) kwargs[str('producer_name')] = 'backend-test' model = onnx.helper.make_model(graph, **kwargs) _NodeTestCases.append(TestCase( name=name, model_name=name, url=None, model_dir=None, model=model, data_sets=[(inputs, outputs)], kind='node', rtol=1e-3, atol=1e-7, )) expanded_function_nodes = function_testcase_helper(node, name) if expanded_function_nodes: function_test_name = name + '_expanded' graph = onnx.helper.make_graph( nodes=expanded_function_nodes, name=function_test_name, inputs=inputs_vi, outputs=outputs_vi) kwargs[str('producer_name')] = 'backend-test' model = onnx.helper.make_model(graph, **kwargs) _NodeTestCases.append(TestCase( name=function_test_name, model_name=function_test_name, url=None, model_dir=None, model=model, data_sets=[(inputs, outputs)], kind='node', rtol=1e-3, atol=1e-7, )) def collect_testcases(): # type: () -> List[TestCase] '''Collect node test cases defined in python/numpy code. ''' import_recursive(sys.modules[__name__]) return _NodeTestCases
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect def argmax_use_numpy(data, axis=0, keepdims=1): # type: (np.ndarray, int, int) -> (np.ndarray) result = np.argmax(data, axis=axis) if (keepdims == 1): result = np.expand_dims(result, axis) return result.astype(np.int64) def argmax_use_numpy_select_last_index(data, axis=0, keepdims=True): # type: (np.ndarray, int, int) -> (np.ndarray) data = np.flip(data, axis) result = np.argmax(data, axis=axis) result = data.shape[axis] - result - 1 if keepdims: result = np.expand_dims(result, axis) return result.astype(np.int64) class ArgMax(Base): @staticmethod def export_no_keepdims(): # type: () -> None data = np.array([[2, 1], [3, 10]], dtype=np.float32) axis = 1 keepdims = 0 node = onnx.helper.make_node( 'ArgMax', inputs=['data'], outputs=['result'], axis=axis, keepdims=keepdims) # result: [[0, 1]] result = argmax_use_numpy(data, axis=axis, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example') data = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32) # result's shape: [2, 4] result = argmax_use_numpy(data, axis=axis, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random') @staticmethod def export_keepdims(): # type: () -> None data = np.array([[2, 1], [3, 10]], dtype=np.float32) axis = 1 keepdims = 1 node = onnx.helper.make_node( 'ArgMax', inputs=['data'], outputs=['result'], axis=axis, keepdims=keepdims) # result: [[0], [1]] result = argmax_use_numpy(data, axis=axis, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example') data = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32) # result's shape: [2, 1, 4] result = argmax_use_numpy(data, axis=axis, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random') @staticmethod def export_default_axes_keepdims(): # type: () -> None data = np.array([[2, 1], [3, 10]], dtype=np.float32) keepdims = 1 node = onnx.helper.make_node( 'ArgMax', inputs=['data'], outputs=['result'], keepdims=keepdims) # result: [[1], [1]] result = argmax_use_numpy(data, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example') data = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32) # result's shape: [1, 3, 4] result = argmax_use_numpy(data, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random') @staticmethod def export_negative_axis_keepdims(): # type: () -> None data = np.array([[2, 1], [3, 10]], dtype=np.float32) axis = -1 keepdims = 1 node = onnx.helper.make_node( 'ArgMax', inputs=['data'], outputs=['result'], axis=axis, keepdims=keepdims) # result: [[0], [1]] result = argmax_use_numpy(data, axis=axis, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example') data = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32) # result's shape: [2, 3, 1] result = argmax_use_numpy(data, axis=axis, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random') @staticmethod def export_no_keepdims_select_last_index(): # type: () -> None data = np.array([[2, 2], [3, 10]], dtype=np.float32) axis = 1 keepdims = 0 node = onnx.helper.make_node( 'ArgMax', inputs=['data'], outputs=['result'], axis=axis, keepdims=keepdims, select_last_index=True) # result: [[1, 1]] result = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example_select_last_index') data = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32) # result's shape: [2, 4] result = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random_select_last_index') @staticmethod def export_keepdims_select_last_index(): # type: () -> None data = np.array([[2, 2], [3, 10]], dtype=np.float32) axis = 1 keepdims = 1 node = onnx.helper.make_node( 'ArgMax', inputs=['data'], outputs=['result'], axis=axis, keepdims=keepdims, select_last_index=True) # result: [[1], [1]] result = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example_select_last_index') data = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32) # result's shape: [2, 1, 4] result = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random_select_last_index') @staticmethod def export_default_axes_keepdims_select_last_index(): # type: () -> None data = np.array([[2, 2], [3, 10]], dtype=np.float32) keepdims = 1 node = onnx.helper.make_node( 'ArgMax', inputs=['data'], outputs=['result'], keepdims=keepdims, select_last_index=True) # result: [[1, 1]] result = argmax_use_numpy_select_last_index(data, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example_select_last_index') data = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32) # result's shape: [1, 3, 4] result = argmax_use_numpy_select_last_index(data, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random_select_last_index') @staticmethod def export_negative_axis_keepdims_select_last_index(): # type: () -> None data = np.array([[2, 2], [3, 10]], dtype=np.float32) axis = -1 keepdims = 1 node = onnx.helper.make_node( 'ArgMax', inputs=['data'], outputs=['result'], axis=axis, keepdims=keepdims, select_last_index=True) # result: [[1], [1]] result = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example_select_last_index') data = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32) # result's shape: [2, 3, 1] result = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims) expect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random_select_last_index')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class BitShift(Base): @staticmethod def export_right_unit8(): # type: () -> None node = onnx.helper.make_node( 'BitShift', inputs=['x', 'y'], outputs=['z'], direction="RIGHT" ) x = np.array([16, 4, 1]).astype(np.uint8) y = np.array([1, 2, 3]).astype(np.uint8) z = x >> y # expected output [8, 1, 0] expect(node, inputs=[x, y], outputs=[z], name='test_bitshift_right_uint8') @staticmethod def export_right_unit16(): # type: () -> None node = onnx.helper.make_node( 'BitShift', inputs=['x', 'y'], outputs=['z'], direction="RIGHT" ) x = np.array([16, 4, 1]).astype(np.uint16) y = np.array([1, 2, 3]).astype(np.uint16) z = x >> y # expected output [8, 1, 0] expect(node, inputs=[x, y], outputs=[z], name='test_bitshift_right_uint16') @staticmethod def export_right_unit32(): # type: () -> None node = onnx.helper.make_node( 'BitShift', inputs=['x', 'y'], outputs=['z'], direction="RIGHT" ) x = np.array([16, 4, 1]).astype(np.uint32) y = np.array([1, 2, 3]).astype(np.uint32) z = x >> y # expected output [8, 1, 0] expect(node, inputs=[x, y], outputs=[z], name='test_bitshift_right_uint32') @staticmethod def export_right_unit64(): # type: () -> None node = onnx.helper.make_node( 'BitShift', inputs=['x', 'y'], outputs=['z'], direction="RIGHT" ) x = np.array([16, 4, 1]).astype(np.uint64) y = np.array([1, 2, 3]).astype(np.uint64) z = x >> y # expected output [8, 1, 0] expect(node, inputs=[x, y], outputs=[z], name='test_bitshift_right_uint64') @staticmethod def export_left_unit8(): # type: () -> None node = onnx.helper.make_node( 'BitShift', inputs=['x', 'y'], outputs=['z'], direction="LEFT" ) x = np.array([16, 4, 1]).astype(np.uint8) y = np.array([1, 2, 3]).astype(np.uint8) z = x << y # expected output [32, 16, 8] expect(node, inputs=[x, y], outputs=[z], name='test_bitshift_left_uint8') @staticmethod def export_left_unit16(): # type: () -> None node = onnx.helper.make_node( 'BitShift', inputs=['x', 'y'], outputs=['z'], direction="LEFT" ) x = np.array([16, 4, 1]).astype(np.uint16) y = np.array([1, 2, 3]).astype(np.uint16) z = x << y # expected output [32, 16, 8] expect(node, inputs=[x, y], outputs=[z], name='test_bitshift_left_uint16') @staticmethod def export_left_unit32(): # type: () -> None node = onnx.helper.make_node( 'BitShift', inputs=['x', 'y'], outputs=['z'], direction="LEFT" ) x = np.array([16, 4, 1]).astype(np.uint32) y = np.array([1, 2, 3]).astype(np.uint32) z = x << y # expected output [32, 16, 8] expect(node, inputs=[x, y], outputs=[z], name='test_bitshift_left_uint32') @staticmethod def export_left_unit64(): # type: () -> None node = onnx.helper.make_node( 'BitShift', inputs=['x', 'y'], outputs=['z'], direction="LEFT" ) x = np.array([16, 4, 1]).astype(np.uint64) y = np.array([1, 2, 3]).astype(np.uint64) z = x << y # expected output [32, 16, 8] expect(node, inputs=[x, y], outputs=[z], name='test_bitshift_left_uint64')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Floor(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Floor', inputs=['x'], outputs=['y'], ) x = np.array([-1.5, 1.2, 2]).astype(np.float32) y = np.floor(x) # expected output [-2., 1., 2.] expect(node, inputs=[x], outputs=[y], name='test_floor_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.floor(x) expect(node, inputs=[x], outputs=[y], name='test_floor')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import math import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Erf(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Erf', inputs=['x'], outputs=['y'], ) x = np.random.randn(1, 3, 32, 32).astype(np.float32) y = np.vectorize(math.erf)(x).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_erf')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect from onnx import helper class Upsample(Base): @staticmethod def export_nearest(): # type: () -> None node = onnx.helper.make_node( 'Upsample', inputs=['X', 'scales'], outputs=['Y'], mode='nearest', ) data = np.array([[[ [1, 2], [3, 4], ]]], dtype=np.float32) scales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32) output = np.array([[[ [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 4], ]]], dtype=np.float32) expect(node, inputs=[data, scales], outputs=[output], name='test_upsample_nearest', opset_imports=[helper.make_opsetid("", 9)])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class ConvInteger(Base): @staticmethod def export(): # type: () -> None x = np.array([2, 3, 4, 5, 6, 7, 8, 9, 10]).astype(np.uint8).reshape((1, 1, 3, 3)) x_zero_point = np.uint8(1) w = np.array([1, 1, 1, 1]).astype(np.uint8).reshape((1, 1, 2, 2)) y = np.array([12, 16, 24, 28]).astype(np.int32).reshape(1, 1, 2, 2) # ConvInteger without padding convinteger_node = onnx.helper.make_node('ConvInteger', inputs=['x', 'w', 'x_zero_point'], outputs=['y']) expect(convinteger_node, inputs=[x, w, x_zero_point], outputs=[y], name='test_basic_convinteger') # ConvInteger with padding y_with_padding = np.array([1, 3, 5, 3, 5, 12, 16, 9, 11, 24, 28, 15, 7, 15, 17, 9]).astype(np.int32).reshape((1, 1, 4, 4)) convinteger_node_with_padding = onnx.helper.make_node('ConvInteger', inputs=['x', 'w', 'x_zero_point'], outputs=['y'], pads=[1, 1, 1, 1],) expect(convinteger_node_with_padding, inputs=[x, w, x_zero_point], outputs=[y_with_padding], name='test_convinteger_with_padding')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class LogSoftmax(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'LogSoftmax', inputs=['x'], outputs=['y'], ) x = np.array([[-1, 0, 1]]).astype(np.float32) # expected output [[-2.40760589, -1.40760589, -0.40760589]] y = x - np.log(np.sum(np.exp(x), axis=1)) expect(node, inputs=[x], outputs=[y], name='test_logsoftmax_example_1') @staticmethod def export_logsoftmax_axis(): # type: () -> None def logsoftmax_2d(x): # type: (np.ndarray) -> np.ndarray max_x = np.max(x, axis=1).reshape((-1, 1)) exp_x = np.exp(x - max_x) return x - max_x - np.log(np.sum(exp_x, axis=1).reshape((-1, 1))) x = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32) # expected output [[-3.4401896, -2.4401896, -1.44018972, -0.44018969], # [-3.4401896, -2.4401896, -1.44018972, -0.44018969]] y = logsoftmax_2d(x) node = onnx.helper.make_node( 'LogSoftmax', inputs=['x'], outputs=['y'], ) expect(node, inputs=[x], outputs=[y], name='test_logsoftmax_large_number') x = np.abs(np.random.randn(3, 4, 5).astype(np.float32)) node = onnx.helper.make_node( 'LogSoftmax', inputs=['x'], outputs=['y'], axis=0, ) y = logsoftmax_2d(x.reshape(1, 60)).reshape(3, 4, 5) expect(node, inputs=[x], outputs=[y], name='test_logsoftmax_axis_0') node = onnx.helper.make_node( 'LogSoftmax', inputs=['x'], outputs=['y'], axis=1, ) y = logsoftmax_2d(x.reshape(3, 20)).reshape(3, 4, 5) expect(node, inputs=[x], outputs=[y], name='test_logsoftmax_axis_1') # default axis is 1 node = onnx.helper.make_node( 'LogSoftmax', inputs=['x'], outputs=['y'], ) expect(node, inputs=[x], outputs=[y], name='test_logsoftmax_default_axis') node = onnx.helper.make_node( 'LogSoftmax', inputs=['x'], outputs=['y'], axis=2, ) y = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5) expect(node, inputs=[x], outputs=[y], name='test_logsoftmax_axis_2') node = onnx.helper.make_node( 'LogSoftmax', inputs=['x'], outputs=['y'], axis=-1, ) y = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5) expect(node, inputs=[x], outputs=[y], name='test_logsoftmax_negative_axis')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Celu(Base): @staticmethod def export(): # type: () -> None alpha = 2.0 node = onnx.helper.make_node( 'Celu', inputs=['X'], outputs=['Y'], alpha=alpha, ) input_data = np.array([[[[0.8439683], [0.5665144], [0.05836735]], [[0.02916367], [0.12964272], [0.5060197]], [[0.79538304], [0.9411346], [0.9546573]]], [[[0.17730942], [0.46192095], [0.26480448]], [[0.6746842], [0.01665257], [0.62473077]], [[0.9240844], [0.9722341], [0.11965699]]], [[[0.41356155], [0.9129373], [0.59330076]], [[0.81929934], [0.7862604], [0.11799799]], [[0.69248444], [0.54119414], [0.07513223]]]], dtype=np.float32) # Calculate expected output data positive_input = np.maximum(0, input_data) negative_input = np.minimum(0, alpha * (np.exp(input_data / alpha) - 1)) expected_output = positive_input + negative_input expect(node, inputs=[input_data], outputs=[expected_output], name='test_celu')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect def softmaxcrossentropy(x, target, weight=None, reduction='mean', ignore_index=None, get_log_prob=None): # type: ignore input_shape = x.shape if len(input_shape) == 1: raise RuntimeError("Unsupported shape") target_shape = target.shape N = input_shape[0] C = input_shape[1] # compute log_softmax max_x = np.max(x, axis=1, keepdims=True) exp_x = np.exp(x - max_x) p = exp_x / np.sum(exp_x, axis=1, keepdims=True) inp = np.log(p) log_prob = None if get_log_prob is True: log_prob = np.copy(inp) # initialize the positional weights when required gather_weight = None if weight is not None: # setting mode='clip' to deal with ignore_index > C or < 0 cases. # when the target value is > C or < 0, it doesn't matter which value we are # taking in gather_weight, since it will be set to 0 in the following if-block gather_weight = np.take(weight, target, mode='clip') # set `ignore_index`'s loss weight to 0. # The loss tensor will be multiplied by this weight tensor, # so `ingore_index`'s loss value will be eliminated. if ignore_index is not None: gather_weight = np.where(target == ignore_index, 0, gather_weight).astype(dtype=np.float32) elif ignore_index is not None: gather_weight = np.where(target == ignore_index, 0, 1).astype(dtype=np.float32) # if input is 4-d and above, make it 3-d if len(input_shape) != 3: inp = inp.reshape((N, C, -1)) target = target.reshape((N, -1)) # Get a dimension from the reshaped input. # If the original input shape is [N, C, H, W], # the D here should be H * W because we reshape # [N, C, H, W] to [N, C, H * W]. D = inp.shape[2] neg_gather_element_input = np.zeros((N, D), dtype=np.float32) for i in range(N): for d in range(D): if target[i][d] != ignore_index: neg_gather_element_input[i][d] = -inp[i][target[i][d]][d] loss = neg_gather_element_input # if the input was 4-d or above reshape to the right shape if len(input_shape) != 3: loss = loss.reshape(target_shape) # apply the weights when required if gather_weight is not None: loss = gather_weight * loss if reduction == 'mean': loss = loss.sum() / gather_weight.sum() if get_log_prob is True: return loss, log_prob else: return loss if reduction == 'mean': loss = np.mean(loss) elif reduction == 'sum': loss = np.sum(loss) if get_log_prob is True: return loss, log_prob else: return loss class SoftmaxCrossEntropyLoss(Base): @staticmethod def export_softmaxcrossentropy_none(): # type: () -> None # Define operator attributes. reduction = 'none' # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z'], reduction=reduction) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) # Compute SoftmaxCrossEntropyLoss sce = softmaxcrossentropy(x, labels, reduction='none') # Check results expect(node, inputs=[x, labels], outputs=[sce], name='test_softmax_cross_entropy_none') @staticmethod def export_softmaxcrossentropy_none_log_prob(): # type: () -> None # Define operator attributes. reduction = 'none' # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z', 'log_prob'], reduction=reduction) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) # Compute SoftmaxCrossEntropyLoss loss, log_prob = softmaxcrossentropy(x, labels, reduction='none', get_log_prob=True) # Check results expect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_softmax_cross_entropy_none_log_prob') @staticmethod def export_softmaxcrossentropy_none_weights(): # type: () -> None # Define operator attributes. reduction = 'none' # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z'], reduction=reduction) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) weights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32) # Compute SoftmaxCrossEntropyLoss sce = softmaxcrossentropy(x, labels, weight=weights, reduction='none') # Check results expect(node, inputs=[x, labels, weights], outputs=[sce], name='test_softmax_cross_entropy_none_weights') @staticmethod def export_softmaxcrossentropy_none_weights_log_prob(): # type: () -> None # Define operator attributes. reduction = 'none' # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z', 'log_prob'], reduction=reduction) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) weights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32) # Compute SoftmaxCrossEntropyLoss loss, log_prob = softmaxcrossentropy(x, labels, weight=weights, reduction='none', get_log_prob=True) # Check results expect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_softmax_cross_entropy_none_weights_log_prob') @staticmethod def export_softmaxcrossentropy_sum(): # type: () -> None # Define operator attributes. reduction = 'sum' # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z'], reduction=reduction) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) # Compute SoftmaxCrossEntropyLoss sce = softmaxcrossentropy(x, labels, reduction='sum') # Check results expect(node, inputs=[x, labels], outputs=[sce], name='test_softmax_cross_entropy_sum') @staticmethod def export_softmaxcrossentropy_sum_log_prob(): # type: () -> None # Define operator attributes. reduction = 'sum' # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z', 'log_prob'], reduction=reduction) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) # Compute SoftmaxCrossEntropyLoss loss, log_prob = softmaxcrossentropy(x, labels, reduction='sum', get_log_prob=True) # Check results expect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_softmax_cross_entropy_sum_log_prob') @staticmethod def export_softmaxcrossentropy_mean(): # type: () -> None # Define operator attributes. reduction = 'mean' # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z'], reduction=reduction) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) # Compute SoftmaxCrossEntropyLoss sce = softmaxcrossentropy(x, labels) # Check results expect(node, inputs=[x, labels], outputs=[sce], name='test_softmax_cross_entropy_mean') @staticmethod def export_softmaxcrossentropy_mean_log_prob(): # type: () -> None # Define operator attributes. reduction = 'mean' # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z', 'log_prob'], reduction=reduction) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) # Compute SoftmaxCrossEntropyLoss loss, log_prob = softmaxcrossentropy(x, labels, get_log_prob=True) # Check results expect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_softmax_cross_entropy_mean_log_prob') @staticmethod def export_softmaxcrossentropy_mean_3d(): # type: () -> None # Define operator attributes. reduction = 'mean' # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z'], reduction=reduction) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5, 2).astype(np.float32) y = np.random.randint(0, high=5, size=(3, 2)) # Compute SoftmaxCrossEntropyLoss sce = softmaxcrossentropy(x, y) # Check results expect(node, inputs=[x, y], outputs=[sce], name='test_softmax_cross_entropy_mean_3d') @staticmethod def export_softmaxcrossentropy_mean_3d_log_prob(): # type: () -> None # Define operator attributes. reduction = 'mean' # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z', 'log_prob'], reduction=reduction) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5, 2).astype(np.float32) y = np.random.randint(0, high=5, size=(3, 2)) # Compute SoftmaxCrossEntropyLoss loss, log_prob = softmaxcrossentropy(x, y, get_log_prob=True) # Check results expect(node, inputs=[x, y], outputs=[loss, log_prob], name='test_softmax_cross_entropy_mean_3d_log_prob') @staticmethod def export_softmaxcrossentropy_mean_weights(): # type: () -> None # Define operator attributes. reduction = 'mean' # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z'], reduction=reduction) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) weights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32) # Compute SoftmaxCrossEntropyLoss sce = softmaxcrossentropy(x, labels, weight=weights) # Check results expect(node, inputs=[x, labels, weights], outputs=[sce], name='test_softmax_cross_entropy_mean_weight') @staticmethod def export_softmaxcrossentropy_mean_weights_log_prob(): # type: () -> None # Define operator attributes. reduction = 'mean' # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z', 'log_prob'], reduction=reduction) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) weights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32) # Compute SoftmaxCrossEntropyLoss loss, log_prob = softmaxcrossentropy(x, labels, weight=weights, get_log_prob=True) # Check results expect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_softmax_cross_entropy_mean_weight_log_prob') @staticmethod def export_softmaxcrossentropy_mean_weights_ignore_index(): # type: () -> None # Define operator attributes. reduction = 'mean' ignore_index = np.int64(0) # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z'], reduction=reduction, ignore_index=ignore_index) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) labels[0] = np.int64(0) weights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32) # Compute SoftmaxCrossEntropyLoss sce = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index) # Check results expect(node, inputs=[x, labels, weights], outputs=[sce], name='test_softmax_cross_entropy_mean_weight_ignore_index') @staticmethod def export_softmaxcrossentropy_mean_weights_ignore_index_log_prob(): # type: () -> None # Define operator attributes. reduction = 'mean' ignore_index = np.int64(0) # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z', 'log_prob'], reduction=reduction, ignore_index=ignore_index) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) labels[0] = np.int64(0) weights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32) # Compute SoftmaxCrossEntropyLoss loss, log_prob = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index, get_log_prob=True) # Check results expect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_softmax_cross_entropy_mean_weight_ignore_index_log_prob') @staticmethod def export_softmaxcrossentropy_mean_no_weights_ignore_index(): # type: () -> None # Define operator attributes. reduction = 'mean' ignore_index = np.int64(2) # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z'], reduction=reduction, ignore_index=ignore_index) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) labels[0] = np.int64(2) # Compute SoftmaxCrossEntropyLoss sce = softmaxcrossentropy(x, labels, ignore_index=ignore_index) # Check results expect(node, inputs=[x, labels], outputs=[sce], name='test_softmax_cross_entropy_mean_no_weight_ignore_index') @staticmethod def export_softmaxcrossentropy_mean_no_weights_ignore_index_log_prob(): # type: () -> None # Define operator attributes. reduction = 'mean' ignore_index = np.int64(2) # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z', 'log_prob'], reduction=reduction, ignore_index=ignore_index) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, )) labels[0] = np.int64(2) # Compute SoftmaxCrossEntropyLoss loss, log_prob = softmaxcrossentropy(x, labels, ignore_index=ignore_index, get_log_prob=True) # Check results expect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_softmax_cross_entropy_mean_no_weight_ignore_index_log_prob') @staticmethod def export_softmaxcrossentropy_mean_weights_ignore_index_3d(): # type: () -> None # Define operator attributes. reduction = 'mean' ignore_index = np.int64(1) # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z'], reduction=reduction, ignore_index=ignore_index) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5, 2).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, 2)) labels[0][0] = np.int64(1) weights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32) # Compute SoftmaxCrossEntropyLoss sce = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index) # Check results expect(node, inputs=[x, labels, weights], outputs=[sce], name='test_softmax_cross_entropy_mean_weight_ignore_index_3d') @staticmethod def export_softmaxcrossentropy_mean_weights_ignore_index_3d_log_prob(): # type: () -> None # Define operator attributes. reduction = 'mean' ignore_index = np.int64(1) # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z', 'log_prob'], reduction=reduction, ignore_index=ignore_index) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5, 2).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, 2)) labels[0][0] = np.int64(1) weights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32) # Compute SoftmaxCrossEntropyLoss loss, log_prob = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index, get_log_prob=True) # Check results expect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_softmax_cross_entropy_mean_weight_ignore_index_3d_log_prob') @staticmethod def export_softmaxcrossentropy_mean_no_weights_ignore_index_3d(): # type: () -> None # Define operator attributes. reduction = 'mean' ignore_index = np.int64(2) # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z'], reduction=reduction, ignore_index=ignore_index) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5, 2).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, 2)) labels[0][0] = np.int64(2) # Compute SoftmaxCrossEntropyLoss sce = softmaxcrossentropy(x, labels, ignore_index=ignore_index) # Check results expect(node, inputs=[x, labels], outputs=[sce], name='test_softmax_cross_entropy_mean_no_weight_ignore_index_3d') @staticmethod def export_softmaxcrossentropy_mean_no_weights_ignore_index_3d_log_prob(): # type: () -> None # Define operator attributes. reduction = 'mean' ignore_index = np.int64(2) # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z', 'log_prob'], reduction=reduction, ignore_index=ignore_index) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5, 2).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, 2)) labels[0][0] = np.int64(2) # Compute SoftmaxCrossEntropyLoss loss, log_prob = softmaxcrossentropy(x, labels, ignore_index=ignore_index, get_log_prob=True) # Check results expect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_softmax_cross_entropy_mean_no_weight_ignore_index_3d_log_prob') @staticmethod def export_softmaxcrossentropy_mean_weights_ignore_index_4d(): # type: () -> None # Define operator attributes. reduction = 'mean' ignore_index = np.int64(2) # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z'], reduction=reduction, ignore_index=ignore_index) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5, 2, 7).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, 2, 7)) labels[0][0][0] = np.int64(2) weights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32) # Compute SoftmaxCrossEntropyLoss sce = softmaxcrossentropy(x, labels, reduction=reduction, weight=weights, ignore_index=ignore_index) # Check results expect(node, inputs=[x, labels, weights], outputs=[sce], name='test_softmax_cross_entropy_mean_weight_ignore_index_4d') @staticmethod def export_softmaxcrossentropy_mean_weights_ignore_index_4d_log_prob(): # type: () -> None # Define operator attributes. reduction = 'mean' ignore_index = np.int64(2) # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z', 'log_prob'], reduction=reduction, ignore_index=ignore_index) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5, 2, 7).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, 2, 7)) labels[0][0][0] = np.int64(2) weights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32) # Compute SoftmaxCrossEntropyLoss loss, log_prob = softmaxcrossentropy(x, labels, reduction=reduction, weight=weights, ignore_index=ignore_index, get_log_prob=True) # Check results expect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_softmax_cross_entropy_mean_weight_ignore_index_4d_log_prob') @staticmethod def export_softmaxcrossentropy_mean_no_weights_ignore_index_4d(): # type: () -> None # Define operator attributes. reduction = 'mean' ignore_index = np.int64(2) # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z'], reduction=reduction, ignore_index=ignore_index) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5, 2, 7).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, 2, 7)) labels[0][0][0] = np.int64(2) # Compute SoftmaxCrossEntropyLoss sce = softmaxcrossentropy(x, labels, reduction=reduction, ignore_index=ignore_index) # Check results expect(node, inputs=[x, labels], outputs=[sce], name='test_softmax_cross_entropy_mean_no_weight_ignore_index_4d') @staticmethod def export_softmaxcrossentropy_mean_no_weights_ignore_index_4d_log_prob(): # type: () -> None # Define operator attributes. reduction = 'mean' ignore_index = np.int64(2) # Create operator. node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z', 'log_prob'], reduction=reduction, ignore_index=ignore_index) # Define operator inputs. np.random.seed(0) x = np.random.rand(3, 5, 2, 7).astype(np.float32) labels = np.random.randint(0, high=5, size=(3, 2, 7)) labels[0][0][0] = np.int64(2) # Compute SoftmaxCrossEntropyLoss loss, log_prob = softmaxcrossentropy(x, labels, reduction=reduction, ignore_index=ignore_index, get_log_prob=True) # Check results expect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_softmax_cross_entropy_mean_no_weight_ignore_index_4d_log_prob') @staticmethod def export_input_shape_is_NCd1d2d3d4d5_mean_weight(): # type: () -> None reduction = 'mean' node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z'], reduction=reduction) N, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4 np.random.seed(0) x = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32) labels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5)) weight = np.random.rand(C).astype(np.float32) sce = softmaxcrossentropy(x, labels, weight=weight, reduction=reduction) expect(node, inputs=[x, labels, weight], outputs=[sce], name='test_softmax_cross_entropy_input_shape_is_NCd1d2d3d4d5_mean_weight') @staticmethod def export_input_shape_is_NCd1d2d3d4d5_mean_weight_log_prob(): # type: () -> None reduction = 'mean' node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z', 'log_prob'], reduction=reduction) N, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4 np.random.seed(0) x = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32) labels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5)) weight = np.random.rand(C).astype(np.float32) loss, log_prob = softmaxcrossentropy(x, labels, weight=weight, reduction=reduction, get_log_prob=True) expect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_softmax_cross_entropy_input_shape_is_NCd1d2d3d4d5_mean_weight_log_prob') @staticmethod def export_input_shape_is_NCd1d2d3d4d5_none_no_weight(): # type: () -> None reduction = 'none' node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z'], reduction=reduction) N, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4 np.random.seed(0) x = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32) labels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5)) sce = softmaxcrossentropy(x, labels, reduction=reduction) expect(node, inputs=[x, labels], outputs=[sce], name='test_softmax_cross_entropy_input_shape_is_NCd1d2d3d4d5_none_no_weight') @staticmethod def export_input_shape_is_NCd1d2d3d4d5_none_no_weight_log_prob(): # type: () -> None reduction = 'none' node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z', 'log_prob'], reduction=reduction) N, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4 np.random.seed(0) x = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32) labels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5)) loss, log_prob = softmaxcrossentropy(x, labels, reduction=reduction, get_log_prob=True) expect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_softmax_cross_entropy_input_shape_is_NCd1d2d3d4d5_none_no_weight_log_prob') @staticmethod def export_input_shape_is_NCd1_mean_weight_negative_ignore_index(): # type: () -> None reduction = 'mean' ignore_index = np.int64(-1) node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z'], reduction=reduction, ignore_index=ignore_index) N, C, dim1 = 3, 5, 6 np.random.seed(0) x = np.random.rand(N, C, dim1).astype(np.float32) labels = np.random.randint(0, high=C, size=(N, dim1)) labels[0][0] = -1 weight = np.random.rand(C).astype(np.float32) sce = softmaxcrossentropy(x, labels, weight=weight, reduction=reduction, ignore_index=ignore_index) expect(node, inputs=[x, labels, weight], outputs=[sce], name='test_softmax_cross_entropy_input_shape_is_NCd1_mean_weight_negative_ignore_index') @staticmethod def export_input_shape_is_NCd1_mean_weight_negative_ignore_index_log_prob(): # type: () -> None reduction = 'mean' ignore_index = np.int64(-1) node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z', 'log_prob'], reduction=reduction, ignore_index=ignore_index) N, C, dim1 = 3, 5, 6 np.random.seed(0) x = np.random.rand(N, C, dim1).astype(np.float32) labels = np.random.randint(0, high=C, size=(N, dim1)) labels[0][0] = -1 weight = np.random.rand(C).astype(np.float32) loss, log_prob = softmaxcrossentropy(x, labels, weight=weight, reduction=reduction, ignore_index=ignore_index, get_log_prob=True) expect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_softmax_cross_entropy_input_shape_is_NCd1_mean_weight_negative_ignore_index_log_prob') @staticmethod def export_input_shape_is_NCd1d2d3_none_no_weight_negative_ignore_index(): # type: () -> None reduction = 'none' ignore_index = np.int64(-5) node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z'], reduction=reduction, ignore_index=ignore_index) N, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5 np.random.seed(0) x = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32) labels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3)) labels[0][0][0][0] = -5 sce = softmaxcrossentropy(x, labels, reduction=reduction, ignore_index=ignore_index) expect(node, inputs=[x, labels], outputs=[sce], name='test_softmax_cross_entropy_input_shape_is_NCd1d2d3_none_no_weight_negative_ignore_index') @staticmethod def export_input_shape_is_NCd1d2d3_none_no_weight_negative_ignore_index_log_prob(): # type: () -> None reduction = 'none' ignore_index = np.int64(-5) node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y'], outputs=['z', 'log_prob'], reduction=reduction, ignore_index=ignore_index) N, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5 np.random.seed(0) x = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32) labels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3)) labels[0][0][0][0] = -5 loss, log_prob = softmaxcrossentropy(x, labels, reduction=reduction, ignore_index=ignore_index, get_log_prob=True) expect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_softmax_cross_entropy_input_shape_is_NCd1d2d3_none_no_weight_negative_ignore_index_log_prob') @staticmethod def export_input_shape_is_NCd1d2d3_sum_weight_high_ignore_index(): # type: () -> None reduction = 'sum' ignore_index = np.int64(10) node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z'], reduction=reduction, ignore_index=ignore_index) N, C = 3, 5 np.random.seed(0) x = np.random.rand(N, C).astype(np.float32) labels = np.random.randint(0, high=C, size=(N)) labels[0] = 10 weight = np.random.rand(C).astype(np.float32) sce = softmaxcrossentropy(x, labels, weight=weight, reduction=reduction, ignore_index=ignore_index) expect(node, inputs=[x, labels, weight], outputs=[sce], name='test_softmax_cross_entropy_input_shape_is_NCd1d2d3_sum_weight_high_ignore_index') @staticmethod def export_input_shape_is_NCd1d2d3_sum_weight_high_ignore_index_log_prob(): # type: () -> None reduction = 'sum' ignore_index = np.int64(10) node = onnx.helper.make_node('SoftmaxCrossEntropyLoss', inputs=['x', 'y', 'w'], outputs=['z', 'log_prob'], reduction=reduction, ignore_index=ignore_index) N, C = 3, 5 np.random.seed(0) x = np.random.rand(N, C).astype(np.float32) labels = np.random.randint(0, high=C, size=(N)) labels[0] = 10 weight = np.random.rand(C).astype(np.float32) loss, log_prob = softmaxcrossentropy(x, labels, weight=weight, reduction=reduction, ignore_index=ignore_index, get_log_prob=True) expect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_softmax_cross_entropy_input_shape_is_NCd1d2d3_sum_weight_high_ignore_index_log_prob')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class RoiAlign(Base): @staticmethod def export_roialign(): # type: () -> None node = onnx.helper.make_node( "RoiAlign", inputs=["X", "rois", "batch_indices"], outputs=["Y"], spatial_scale=1.0, output_height=5, output_width=5, sampling_ratio=2, ) X = np.array( [ [ [ [ 0.2764, 0.7150, 0.1958, 0.3416, 0.4638, 0.0259, 0.2963, 0.6518, 0.4856, 0.7250, ], [ 0.9637, 0.0895, 0.2919, 0.6753, 0.0234, 0.6132, 0.8085, 0.5324, 0.8992, 0.4467, ], [ 0.3265, 0.8479, 0.9698, 0.2471, 0.9336, 0.1878, 0.4766, 0.4308, 0.3400, 0.2162, ], [ 0.0206, 0.1720, 0.2155, 0.4394, 0.0653, 0.3406, 0.7724, 0.3921, 0.2541, 0.5799, ], [ 0.4062, 0.2194, 0.4473, 0.4687, 0.7109, 0.9327, 0.9815, 0.6320, 0.1728, 0.6119, ], [ 0.3097, 0.1283, 0.4984, 0.5068, 0.4279, 0.0173, 0.4388, 0.0430, 0.4671, 0.7119, ], [ 0.1011, 0.8477, 0.4726, 0.1777, 0.9923, 0.4042, 0.1869, 0.7795, 0.9946, 0.9689, ], [ 0.1366, 0.3671, 0.7011, 0.6234, 0.9867, 0.5585, 0.6985, 0.5609, 0.8788, 0.9928, ], [ 0.5697, 0.8511, 0.6711, 0.9406, 0.8751, 0.7496, 0.1650, 0.1049, 0.1559, 0.2514, ], [ 0.7012, 0.4056, 0.7879, 0.3461, 0.0415, 0.2998, 0.5094, 0.3727, 0.5482, 0.0502, ], ] ] ], dtype=np.float32, ) batch_indices = np.array([0, 0, 0], dtype=np.int64) rois = np.array([[0, 0, 9, 9], [0, 5, 4, 9], [5, 5, 9, 9]], dtype=np.float32) # (num_rois, C, output_height, output_width) Y = np.array( [ [ [ [0.4664, 0.4466, 0.3405, 0.5688, 0.6068], [0.3714, 0.4296, 0.3835, 0.5562, 0.3510], [0.2768, 0.4883, 0.5222, 0.5528, 0.4171], [0.4713, 0.4844, 0.6904, 0.4920, 0.8774], [0.6239, 0.7125, 0.6289, 0.3355, 0.3495], ] ], [ [ [0.3022, 0.4305, 0.4696, 0.3978, 0.5423], [0.3656, 0.7050, 0.5165, 0.3172, 0.7015], [0.2912, 0.5059, 0.6476, 0.6235, 0.8299], [0.5916, 0.7389, 0.7048, 0.8372, 0.8893], [0.6227, 0.6153, 0.7097, 0.6154, 0.4585], ] ], [ [ [0.2384, 0.3379, 0.3717, 0.6100, 0.7601], [0.3767, 0.3785, 0.7147, 0.9243, 0.9727], [0.5749, 0.5826, 0.5709, 0.7619, 0.8770], [0.5355, 0.2566, 0.2141, 0.2796, 0.3600], [0.4365, 0.3504, 0.2887, 0.3661, 0.2349], ] ], ], dtype=np.float32, ) expect(node, inputs=[X, rois, batch_indices], outputs=[Y], name="test_roialign")
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Ceil(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Ceil', inputs=['x'], outputs=['y'], ) x = np.array([-1.5, 1.2]).astype(np.float32) y = np.ceil(x) # expected output [-1., 2.] expect(node, inputs=[x], outputs=[y], name='test_ceil_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.ceil(x) expect(node, inputs=[x], outputs=[y], name='test_ceil')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Size(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Size', inputs=['x'], outputs=['y'], ) x = np.array([ [1, 2, 3], [4, 5, 6], ]).astype(np.float32) y = np.array(6).astype(np.int64) expect(node, inputs=[x], outputs=[y], name='test_size_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.array(x.size).astype(np.int64) expect(node, inputs=[x], outputs=[y], name='test_size')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class NonMaxSuppression(Base): @staticmethod def export_nonmaxsuppression_suppress_by_IOU(): # type: () -> None node = onnx.helper.make_node( 'NonMaxSuppression', inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'], outputs=['selected_indices'] ) boxes = np.array([[ [0.0, 0.0, 1.0, 1.0], [0.0, 0.1, 1.0, 1.1], [0.0, -0.1, 1.0, 0.9], [0.0, 10.0, 1.0, 11.0], [0.0, 10.1, 1.0, 11.1], [0.0, 100.0, 1.0, 101.0] ]]).astype(np.float32) scores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32) max_output_boxes_per_class = np.array([3]).astype(np.int64) iou_threshold = np.array([0.5]).astype(np.float32) score_threshold = np.array([0.0]).astype(np.float32) selected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64) expect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_suppress_by_IOU') @staticmethod def export_nonmaxsuppression_suppress_by_IOU_and_scores(): # type: () -> None node = onnx.helper.make_node( 'NonMaxSuppression', inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'], outputs=['selected_indices'] ) boxes = np.array([[ [0.0, 0.0, 1.0, 1.0], [0.0, 0.1, 1.0, 1.1], [0.0, -0.1, 1.0, 0.9], [0.0, 10.0, 1.0, 11.0], [0.0, 10.1, 1.0, 11.1], [0.0, 100.0, 1.0, 101.0] ]]).astype(np.float32) scores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32) max_output_boxes_per_class = np.array([3]).astype(np.int64) iou_threshold = np.array([0.5]).astype(np.float32) score_threshold = np.array([0.4]).astype(np.float32) selected_indices = np.array([[0, 0, 3], [0, 0, 0]]).astype(np.int64) expect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_suppress_by_IOU_and_scores') @staticmethod def export_nonmaxsuppression_flipped_coordinates(): # type: () -> None node = onnx.helper.make_node( 'NonMaxSuppression', inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'], outputs=['selected_indices'] ) boxes = np.array([[ [1.0, 1.0, 0.0, 0.0], [0.0, 0.1, 1.0, 1.1], [0.0, 0.9, 1.0, -0.1], [0.0, 10.0, 1.0, 11.0], [1.0, 10.1, 0.0, 11.1], [1.0, 101.0, 0.0, 100.0] ]]).astype(np.float32) scores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32) max_output_boxes_per_class = np.array([3]).astype(np.int64) iou_threshold = np.array([0.5]).astype(np.float32) score_threshold = np.array([0.0]).astype(np.float32) selected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64) expect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_flipped_coordinates') @staticmethod def export_nonmaxsuppression_limit_output_size(): # type: () -> None node = onnx.helper.make_node( 'NonMaxSuppression', inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'], outputs=['selected_indices'] ) boxes = np.array([[ [0.0, 0.0, 1.0, 1.0], [0.0, 0.1, 1.0, 1.1], [0.0, -0.1, 1.0, 0.9], [0.0, 10.0, 1.0, 11.0], [0.0, 10.1, 1.0, 11.1], [0.0, 100.0, 1.0, 101.0] ]]).astype(np.float32) scores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32) max_output_boxes_per_class = np.array([2]).astype(np.int64) iou_threshold = np.array([0.5]).astype(np.float32) score_threshold = np.array([0.0]).astype(np.float32) selected_indices = np.array([[0, 0, 3], [0, 0, 0]]).astype(np.int64) expect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_limit_output_size') @staticmethod def export_nonmaxsuppression_single_box(): # type: () -> None node = onnx.helper.make_node( 'NonMaxSuppression', inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'], outputs=['selected_indices'] ) boxes = np.array([[ [0.0, 0.0, 1.0, 1.0] ]]).astype(np.float32) scores = np.array([[[0.9]]]).astype(np.float32) max_output_boxes_per_class = np.array([3]).astype(np.int64) iou_threshold = np.array([0.5]).astype(np.float32) score_threshold = np.array([0.0]).astype(np.float32) selected_indices = np.array([[0, 0, 0]]).astype(np.int64) expect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_single_box') @staticmethod def export_nonmaxsuppression_identical_boxes(): # type: () -> None node = onnx.helper.make_node( 'NonMaxSuppression', inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'], outputs=['selected_indices'] ) boxes = np.array([[ [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0] ]]).astype(np.float32) scores = np.array([[[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9]]]).astype(np.float32) max_output_boxes_per_class = np.array([3]).astype(np.int64) iou_threshold = np.array([0.5]).astype(np.float32) score_threshold = np.array([0.0]).astype(np.float32) selected_indices = np.array([[0, 0, 0]]).astype(np.int64) expect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_identical_boxes') @staticmethod def export_nonmaxsuppression_center_point_box_format(): # type: () -> None node = onnx.helper.make_node( 'NonMaxSuppression', inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'], outputs=['selected_indices'], center_point_box=1 ) boxes = np.array([[ [0.5, 0.5, 1.0, 1.0], [0.5, 0.6, 1.0, 1.0], [0.5, 0.4, 1.0, 1.0], [0.5, 10.5, 1.0, 1.0], [0.5, 10.6, 1.0, 1.0], [0.5, 100.5, 1.0, 1.0] ]]).astype(np.float32) scores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32) max_output_boxes_per_class = np.array([3]).astype(np.int64) iou_threshold = np.array([0.5]).astype(np.float32) score_threshold = np.array([0.0]).astype(np.float32) selected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64) expect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_center_point_box_format') @staticmethod def export_nonmaxsuppression_two_classes(): # type: () -> None node = onnx.helper.make_node( 'NonMaxSuppression', inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'], outputs=['selected_indices'] ) boxes = np.array([[ [0.0, 0.0, 1.0, 1.0], [0.0, 0.1, 1.0, 1.1], [0.0, -0.1, 1.0, 0.9], [0.0, 10.0, 1.0, 11.0], [0.0, 10.1, 1.0, 11.1], [0.0, 100.0, 1.0, 101.0] ]]).astype(np.float32) scores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3], [0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32) max_output_boxes_per_class = np.array([2]).astype(np.int64) iou_threshold = np.array([0.5]).astype(np.float32) score_threshold = np.array([0.0]).astype(np.float32) selected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 1, 3], [0, 1, 0]]).astype(np.int64) expect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_two_classes') @staticmethod def export_nonmaxsuppression_two_batches(): # type: () -> None node = onnx.helper.make_node( 'NonMaxSuppression', inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'], outputs=['selected_indices'] ) boxes = np.array([[[0.0, 0.0, 1.0, 1.0], [0.0, 0.1, 1.0, 1.1], [0.0, -0.1, 1.0, 0.9], [0.0, 10.0, 1.0, 11.0], [0.0, 10.1, 1.0, 11.1], [0.0, 100.0, 1.0, 101.0]], [[0.0, 0.0, 1.0, 1.0], [0.0, 0.1, 1.0, 1.1], [0.0, -0.1, 1.0, 0.9], [0.0, 10.0, 1.0, 11.0], [0.0, 10.1, 1.0, 11.1], [0.0, 100.0, 1.0, 101.0]]]).astype(np.float32) scores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]], [[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32) max_output_boxes_per_class = np.array([2]).astype(np.int64) iou_threshold = np.array([0.5]).astype(np.float32) score_threshold = np.array([0.0]).astype(np.float32) selected_indices = np.array([[0, 0, 3], [0, 0, 0], [1, 0, 3], [1, 0, 0]]).astype(np.int64) expect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_two_batches')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect def apply_adagrad(r, t, x, g, h, norm_coefficient, epsilon, decay_factor): # type: ignore # Compute adjusted learning-rate. r_ = r / (1 + t * decay_factor) # Add gradient of regularization term. g_regularized = norm_coefficient * x + g # Update squared accumulated gradient. h_new = h + g_regularized * g_regularized # Compute ADAGRAD's gradient scaling factors h_sqrt = np.sqrt(h_new) + epsilon # Apply ADAGRAD update rule. x_new = x - r_ * g_regularized / h_sqrt return (x_new, h_new) class Adagrad(Base): @staticmethod def export_adagrad(): # type: () -> None # Define operator attributes. norm_coefficient = 0.001 epsilon = 1e-5 decay_factor = 0.1 # Create operator. node = onnx.helper.make_node('Adagrad', inputs=['R', 'T', 'X', 'G', 'H'], outputs=['X_new', 'H_new'], norm_coefficient=norm_coefficient, epsilon=epsilon, decay_factor=decay_factor, domain='ai.onnx.training' ) # Define operator inputs. r = np.array(0.1, dtype=np.float32) # scalar t = np.array(0, dtype=np.int64) # scalar x = np.array([1.0], dtype=np.float32) g = np.array([-1.0], dtype=np.float32) h = np.array([2.0], dtype=np.float32) # Compute expected outputs of Adagrad. x_new, h_new = apply_adagrad(r, t, x, g, h, norm_coefficient, epsilon, decay_factor) # Check results. expect(node, inputs=[r, t, x, g, h], outputs=[x_new, h_new], name='test_adagrad', opset_imports=[onnx.helper.make_opsetid('ai.onnx.training', 1)]) @staticmethod def export_adagrad_multiple(): # type: () -> None # Define operator attributes. norm_coefficient = 0.001 epsilon = 1e-5 decay_factor = 0.1 node = onnx.helper.make_node('Adagrad', inputs=['R', 'T', 'X1', 'X2', 'G1', 'G2', 'H1', 'H2'], outputs=['X1_new', 'X2_new', 'H1_new', 'H2_new'], norm_coefficient=norm_coefficient, epsilon=epsilon, decay_factor=decay_factor, domain='ai.onnx.training' ) # Define operator inputs. r = np.array(0.1, dtype=np.float32) # scalar t = np.array(0, dtype=np.int64) # scalar x1 = np.array([1.0], dtype=np.float32) g1 = np.array([-1.0], dtype=np.float32) h1 = np.array([2.0], dtype=np.float32) x2 = np.array([1.0, 2.0], dtype=np.float32) g2 = np.array([-1.0, -3.0], dtype=np.float32) h2 = np.array([4.0, 1.0], dtype=np.float32) # Compute expected outputs of Adagrad. x1_new, h1_new = apply_adagrad(r, t, x1, g1, h1, norm_coefficient, epsilon, decay_factor) x2_new, h2_new = apply_adagrad(r, t, x2, g2, h2, norm_coefficient, epsilon, decay_factor) # Check results. expect(node, inputs=[r, t, x1, x2, g1, g2, h1, h2], outputs=[x1_new, x2_new, h1_new, h2_new], name='test_adagrad_multiple', opset_imports=[onnx.helper.make_opsetid('ai.onnx.training', 1)])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect from ..utils import all_numeric_dtypes class Min(Base): @staticmethod def export(): # type: () -> None data_0 = np.array([3, 2, 1]).astype(np.float32) data_1 = np.array([1, 4, 4]).astype(np.float32) data_2 = np.array([2, 5, 0]).astype(np.float32) result = np.array([1, 2, 0]).astype(np.float32) node = onnx.helper.make_node( 'Min', inputs=['data_0', 'data_1', 'data_2'], outputs=['result'], ) expect(node, inputs=[data_0, data_1, data_2], outputs=[result], name='test_min_example') node = onnx.helper.make_node( 'Min', inputs=['data_0'], outputs=['result'], ) expect(node, inputs=[data_0], outputs=[data_0], name='test_min_one_input') result = np.minimum(data_0, data_1) node = onnx.helper.make_node( 'Min', inputs=['data_0', 'data_1'], outputs=['result'], ) expect(node, inputs=[data_0, data_1], outputs=[result], name='test_min_two_inputs') @staticmethod def export_min_all_numeric_types(): # type: () -> None for op_dtype in all_numeric_dtypes: data_0 = np.array([3, 2, 1]).astype(op_dtype) data_1 = np.array([1, 4, 4]).astype(op_dtype) result = np.array([1, 2, 1]).astype(op_dtype) node = onnx.helper.make_node( 'Min', inputs=['data_0', 'data_1'], outputs=['result'], ) expect(node, inputs=[data_0, data_1], outputs=[result], name='test_min_{0}'.format(np.dtype(op_dtype).name))
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect from .pool_op_common import get_pad_shape, get_output_shape, pool class AveragePool(Base): @staticmethod def export_averagepool_2d_precomputed_pads(): # type: () -> None """ input_shape: [1, 1, 5, 5] output_shape: [1, 1, 5, 5] pad_shape: [4, 4] -> [2, 2, 2, 2] by axis """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[5, 5], pads=[2, 2, 2, 2] ) x = np.array([[[ [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], ]]]).astype(np.float32) y = np.array([[[[7, 7.5, 8, 8.5, 9], [9.5, 10, 10.5, 11, 11.5], [12, 12.5, 13, 13.5, 14], [14.5, 15, 15.5, 16, 16.5], [17, 17.5, 18, 18.5, 19]]]]).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads') @staticmethod def export_averagepool_2d_precomputed_pads_count_include_pad(): # type: () -> None """ input_shape: [1, 1, 5, 5] output_shape: [1, 1, 5, 5] pad_shape: [4, 4] -> [2, 2, 2, 2] by axis """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[5, 5], pads=[2, 2, 2, 2], count_include_pad=1 ) x = np.array([[[ [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], ]]]).astype(np.float32) y = np.array([[[[2.5200, 3.6000, 4.8000, 4.0800, 3.2400], [4.5600, 6.4000, 8.4000, 7.0400, 5.5200], [7.2000, 10.0000, 13.0000, 10.8000, 8.4000], [6.9600, 9.6000, 12.4000, 10.2400, 7.9200], [6.1200, 8.4000, 10.8000, 8.8800, 6.8400]]]]).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads_count_include_pad') @staticmethod def export_averagepool_2d_precomputed_strides(): # type: () -> None """ input_shape: [1, 1, 5, 5] output_shape: [1, 1, 2, 2] """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[2, 2], strides=[2, 2] ) x = np.array([[[ [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], ]]]).astype(np.float32) y = np.array([[[[4, 6], [14, 16]]]]).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_strides') @staticmethod def export_averagepool_2d_precomputed_same_upper(): # type: () -> None """ input_shape: [1, 1, 5, 5] output_shape: [1, 1, 3, 3] pad_shape: [2, 2] -> [1, 1, 1, 1] by axis """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[3, 3], strides=[2, 2], auto_pad='SAME_UPPER' ) x = np.array([[[ [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], ]]]).astype(np.float32) y = np.array([[[[4, 5.5, 7], [11.5, 13, 14.5], [19, 20.5, 22]]]]).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_same_upper') @staticmethod def export_averagepool_1d_default(): # type: () -> None """ input_shape: [1, 3, 32] output_shape: [1, 3, 31] """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[2], ) x = np.random.randn(1, 3, 32).astype(np.float32) x_shape = np.shape(x) kernel_shape = [2] strides = [1] out_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides) padded = x y = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'AVG') expect(node, inputs=[x], outputs=[y], name='test_averagepool_1d_default') @staticmethod def export_averagepool_2d_default(): # type: () -> None """ input_shape: [1, 3, 32, 32] output_shape: [1, 3, 31, 31] """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[2, 2], ) x = np.random.randn(1, 3, 32, 32).astype(np.float32) x_shape = np.shape(x) kernel_shape = (2, 2) strides = (1, 1) out_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides) padded = x y = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG') expect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_default') @staticmethod def export_averagepool_3d_default(): # type: () -> None """ input_shape: [1, 3, 32, 32, 32] output_shape: [1, 3, 31, 31, 31] """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[2, 2, 2], ) x = np.random.randn(1, 3, 32, 32, 32).astype(np.float32) x_shape = np.shape(x) kernel_shape = [2, 2, 2] strides = [1, 1, 1] out_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides) padded = x y = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'AVG') expect(node, inputs=[x], outputs=[y], name='test_averagepool_3d_default') @staticmethod def export_averagepool_2d_same_upper(): # type: () -> None """ input_shape: [1, 3, 32, 32] output_shape: [1, 3, 32, 32] pad_shape: [1, 1] -> [0, 1, 0, 1] by axis """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[2, 2], auto_pad='SAME_UPPER' ) x = np.random.randn(1, 3, 32, 32).astype(np.float32) x_shape = np.shape(x) kernel_shape = (2, 2) strides = (1, 1) out_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides) pad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape) pad_top = pad_shape[0] // 2 pad_bottom = pad_shape[0] - pad_top pad_left = pad_shape[1] // 2 pad_right = pad_shape[1] - pad_left padded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant', constant_values=np.nan) y = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG') expect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_upper') @staticmethod def export_averagepool_2d_same_lower(): # type: () -> None """ input_shape: [1, 3, 32, 32] output_shape: [1, 3, 32, 32] pad_shape: [1, 1] -> [1, 0, 1, 0] by axis """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[2, 2], auto_pad='SAME_LOWER' ) x = np.random.randn(1, 3, 32, 32).astype(np.float32) x_shape = np.shape(x) kernel_shape = (2, 2) strides = (1, 1) out_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides) pad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape) pad_bottom = pad_shape[0] // 2 pad_top = pad_shape[0] - pad_bottom pad_right = pad_shape[1] // 2 pad_left = pad_shape[1] - pad_right padded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant', constant_values=np.nan) y = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG') expect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_lower') @staticmethod def export_averagepool_2d_pads(): # type: () -> None """ input_shape: [1, 3, 28, 28] output_shape: [1, 3, 30, 30] pad_shape: [4, 4] -> [2, 2, 2, 2] by axis """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[3, 3], pads=[2, 2, 2, 2] ) x = np.random.randn(1, 3, 28, 28).astype(np.float32) x_shape = np.shape(x) kernel_shape = (3, 3) strides = (1, 1) pad_bottom = 2 pad_top = 2 pad_right = 2 pad_left = 2 pad_shape = [pad_top + pad_bottom, pad_left + pad_right] out_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides) padded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant', constant_values=np.nan) y = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG') expect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads') @staticmethod def export_averagepool_2d_pads_count_include_pad(): # type: () -> None """ input_shape: [1, 3, 28, 28] output_shape: [1, 3, 30, 30] pad_shape: [4, 4] -> [2, 2, 2, 2] by axis """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[3, 3], pads=[2, 2, 2, 2], count_include_pad=1, ) x = np.random.randn(1, 3, 28, 28).astype(np.float32) x_shape = np.shape(x) kernel_shape = (3, 3) strides = (1, 1) pad_bottom = 2 pad_top = 2 pad_right = 2 pad_left = 2 pad_shape = [pad_top + pad_bottom, pad_left + pad_right] out_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides) padded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant', constant_values=0) y = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG', count_include_pad=1) expect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads_count_include_pad') @staticmethod def export_averagepool_2d_strides(): # type: () -> None """ input_shape: [1, 3, 32, 32] output_shape: [1, 3, 10, 10] """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[5, 5], strides=[3, 3] ) x = np.random.randn(1, 3, 32, 32).astype(np.float32) x_shape = np.shape(x) kernel_shape = (5, 5) strides = (3, 3) out_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides) padded = x y = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG') expect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_strides') @staticmethod def export_averagepool_2d_ceil(): # type: () -> None """ input_shape: [1, 1, 4, 4] output_shape: [1, 1, 2, 2] """ node = onnx.helper.make_node( 'AveragePool', inputs=['x'], outputs=['y'], kernel_shape=[3, 3], strides=[2, 2], ceil_mode=True ) x = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]]).astype(np.float32) y = np.array([[[ [6, 7.5], [12, 13.5]]]]).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_ceil')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Mean(Base): @staticmethod def export(): # type: () -> None data_0 = np.array([3, 0, 2]).astype(np.float32) data_1 = np.array([1, 3, 4]).astype(np.float32) data_2 = np.array([2, 6, 6]).astype(np.float32) result = np.array([2, 3, 4]).astype(np.float32) node = onnx.helper.make_node( 'Mean', inputs=['data_0', 'data_1', 'data_2'], outputs=['result'], ) expect(node, inputs=[data_0, data_1, data_2], outputs=[result], name='test_mean_example') node = onnx.helper.make_node( 'Mean', inputs=['data_0'], outputs=['result'], ) expect(node, inputs=[data_0], outputs=[data_0], name='test_mean_one_input') result = np.divide(np.add(data_0, data_1), 2.) node = onnx.helper.make_node( 'Mean', inputs=['data_0', 'data_1'], outputs=['result'], ) expect(node, inputs=[data_0, data_1], outputs=[result], name='test_mean_two_inputs')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Not(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Not', inputs=['x'], outputs=['not'], ) # 2d x = (np.random.randn(3, 4) > 0).astype(np.bool) expect(node, inputs=[x], outputs=[np.logical_not(x)], name='test_not_2d') # 3d x = (np.random.randn(3, 4, 5) > 0).astype(np.bool) expect(node, inputs=[x], outputs=[np.logical_not(x)], name='test_not_3d') # 4d x = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool) expect(node, inputs=[x], outputs=[np.logical_not(x)], name='test_not_4d')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Mul(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Mul', inputs=['x', 'y'], outputs=['z'], ) x = np.array([1, 2, 3]).astype(np.float32) y = np.array([4, 5, 6]).astype(np.float32) z = x * y # expected output [4., 10., 18.] expect(node, inputs=[x, y], outputs=[z], name='test_mul_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.random.randn(3, 4, 5).astype(np.float32) z = x * y expect(node, inputs=[x, y], outputs=[z], name='test_mul') @staticmethod def export_mul_broadcast(): # type: () -> None node = onnx.helper.make_node( 'Mul', inputs=['x', 'y'], outputs=['z'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.random.randn(5).astype(np.float32) z = x * y expect(node, inputs=[x, y], outputs=[z], name='test_mul_bcast')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect def pad_impl(data, raw_pads, mode, constant_values=0.0): # type: ignore input_rank = data.ndim if input_rank * 2 != raw_pads.size: raise Exception('The number of elements in raw_pads should be 2 * data_rank') # re-order to np.pad accepted order ((x1_begin, x1_end), (x2_begin, x2_end), ...) pad_width = () for i in range(int(raw_pads.size / 2)): pad_width += ((raw_pads[i], raw_pads[i + input_rank])), # type: ignore if mode == 'constant': y = np.pad( data, pad_width=pad_width, mode=mode, constant_values=constant_values, ) return y y = np.pad( data, pad_width=pad_width, mode=mode, ) return y class Pad(Base): @staticmethod def export_constant_pad(): # type: () -> None node = onnx.helper.make_node( 'Pad', inputs=['x', 'pads', 'value'], outputs=['y'], mode='constant' ) x = np.random.randn(1, 3, 4, 5).astype(np.float32) pads = np.array([0, 0, 1, 3, 0, 0, 2, 4]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...] value = np.float32(1.2) y = pad_impl( x, pads, 'constant', 1.2 ) expect(node, inputs=[x, pads, value], outputs=[y], name='test_constant_pad') @staticmethod def export_reflection_and_edge_pad(): # type: () -> None for mode in ['edge', 'reflect']: node = onnx.helper.make_node( 'Pad', inputs=['x', 'pads'], outputs=['y'], mode=mode ) x = np.random.randn(1, 3, 4, 5).astype(np.int32) pads = np.array([0, 0, 1, 1, 0, 0, 1, 1]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...] y = pad_impl( x, pads, mode ) expect(node, inputs=[x, pads], outputs=[y], name='test_{}_pad'.format(mode))
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class ReduceMean(Base): @staticmethod def export_do_not_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 0 node = onnx.helper.make_node( 'ReduceMean', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[12.5, 1.5] # [35., 1.5] # [57.5, 1.5]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_random') @staticmethod def export_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 1 node = onnx.helper.make_node( 'ReduceMean', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[[12.5, 1.5]] # [[35., 1.5]] # [[57.5, 1.5]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_random') @staticmethod def export_default_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = None keepdims = 1 node = onnx.helper.make_node( 'ReduceMean', inputs=['data'], outputs=['reduced'], keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.mean(data, axis=axes, keepdims=keepdims == 1) #print(reduced) #[[[18.25]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.mean(data, axis=axes, keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_random') @staticmethod def export_negative_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [-2] keepdims = 1 node = onnx.helper.make_node( 'ReduceMean', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1) # print(reduced) # [[[12.5, 1.5]] # [[35., 1.5]] # [[57.5, 1.5]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_random')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect from typing import Any, List, Callable, Union, Optional, Text def cartesian(arrays, out=None): # type: (List[np.ndarray], np.ndarray) -> np.ndarray """ From https://stackoverflow.com/a/1235363 Generate a cartesian product of input arrays. Parameters ---------- arrays : list of array-like 1-D arrays to form the cartesian product of. out : ndarray Array to place the cartesian product in. Returns ------- out : ndarray 2-D array of shape (M, len(arrays)) containing cartesian products formed of input arrays. Examples -------- >>> cartesian(([1, 2, 3], [4, 5], [6, 7])) array([[1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7], [3, 4, 6], [3, 4, 7], [3, 5, 6], [3, 5, 7]]) """ arrays = [np.asarray(x) for x in arrays] dtype = arrays[0].dtype n = np.prod([x.size for x in arrays]) if out is None: out = np.zeros([n, len(arrays)], dtype=dtype) m = n // arrays[0].size out[:, 0] = np.repeat(arrays[0], m) if arrays[1:]: cartesian(arrays[1:], out=out[0:m, 1:]) for j in range(1, arrays[0].size): out[j * m:(j + 1) * m, 1:] = out[0:m, 1:] return out def interpolate_1d_with_x(data, # type: np.ndarray scale_factor, # type: float x, # type: float get_coeffs, # type: Callable[[float], np.ndarray] roi=None, # type: np.ndarray extrapolation_value=0.0, # type: float coordinate_transformation_mode='half_pixel', # type: Text exclude_outside=False, # type: bool ): # type: (...) -> np.ndarray def get_neighbor_idxes(x, n, limit): # type: (float, int, int) -> np.ndarray """ Return the n nearest indexes to x among [0, limit), prefer the indexes smaller than x. As a result, the ratio must be in (0, 1] Examples: get_neighbor_idxes(4, 2, 10) == [3, 4] get_neighbor_idxes(4, 3, 10) == [3, 4, 5] get_neighbor_idxes(4.4, 3, 10) == [3, 4, 5] get_neighbor_idxes(4.5, 3, 10) == [3, 4, 5] get_neighbor_idxes(4.6, 3, 10) == [4, 5, 6] get_neighbor_idxes(4.4, 1, 10) == [4] get_neighbor_idxes(4.6, 1, 10) == [5] :param x: :param n: the number of the wanted indexes :param limit: the maximum value of index :return: An np.array containing n nearest indexes in ascending order """ idxes = sorted(range(limit), key=lambda idx: (abs(x - idx), idx))[:n] idxes = sorted(idxes) return np.array(idxes) def get_neighbor(x, n, data): # type: (float, int, np.ndarray) -> np.ndarray """ Pad `data` in 'edge' mode, and get n nearest elements in the padded array and their indexes in the original array :param x: center index (in the unpadded coordinate system) of the found nearest elements. :param n: the number of neighbors. :param data: the array :return: A tuple containing the indexes of neighbor elements (the index can be smaller than 0 or higher than len(data)) and the value of these elements """ pad_width = np.ceil(n / 2).astype(np.int) padded = np.pad(data, pad_width, mode='edge') x += pad_width idxes = get_neighbor_idxes(x, n, len(padded)) ret = padded[idxes] return idxes - pad_width, ret input_width = len(data) output_width = scale_factor * input_width if coordinate_transformation_mode == 'align_corners': if output_width == 1: x_ori = 0. else: x_ori = x * (input_width - 1) / (output_width - 1) elif coordinate_transformation_mode == 'asymmetric': x_ori = x / scale_factor elif coordinate_transformation_mode == 'tf_crop_and_resize': if output_width == 1: x_ori = (roi[1] - roi[0]) * (input_width - 1) / 2 else: x_ori = x * (roi[1] - roi[0]) * \ (input_width - 1) / (output_width - 1) x_ori += (roi[0] * (input_width - 1)) # Return extrapolation_value directly as what TF CropAndResize does if x_ori < 0 or x_ori > input_width - 1: return extrapolation_value elif coordinate_transformation_mode == 'tf_half_pixel_for_nn': x_ori = (x + 0.5) / scale_factor elif coordinate_transformation_mode == 'pytorch_half_pixel': if output_width == 1: x_ori = -0.5 else: x_ori = (x + 0.5) / scale_factor - 0.5 else: # coordinate_transformation_mode == 'half_pixel' x_ori = (x + 0.5) / scale_factor - 0.5 x_ori_int = np.floor(x_ori).astype(np.int).item() # ratio must be in (0, 1] since we prefer the pixel on the left of `x_ori` if x_ori.is_integer(): ratio = 1 else: ratio = x_ori - x_ori_int coeffs = get_coeffs(ratio) n = len(coeffs) idxes, points = get_neighbor(x_ori, n, data) if exclude_outside: for i, idx in enumerate(idxes): if idx < 0 or idx >= input_width: coeffs[i] = 0 coeffs /= sum(coeffs) return np.dot(coeffs, points).item() def interpolate_nd_with_x(data, # type: np.ndarray n, # type: int scale_factors, # type: List[float] x, # type: List[float] get_coeffs, # type: Callable[[float], np.ndarray] roi=None, # type: np.ndarray **kwargs # type: Any ): # type: (...) -> np.ndarray if n == 1: return interpolate_1d_with_x(data, scale_factors[0], x[0], get_coeffs, roi=roi, **kwargs) return interpolate_1d_with_x( [interpolate_nd_with_x(data[i], n - 1, scale_factors[1:], x[1:], get_coeffs, roi=None if roi is None else np.concatenate( [roi[1:n], roi[n + 1:]]), **kwargs) for i in range(data.shape[0])], scale_factors[0], x[0], get_coeffs, roi=None if roi is None else [roi[0], roi[n]], **kwargs) def interpolate_nd(data, # type: np.ndarray get_coeffs, # type: Callable[[float], np.ndarray] output_size=None, # type: Optional[List[int]] scale_factors=None, # type: Optional[List[float]] roi=None, # type: np.ndarray **kwargs # type: Any ): # type: (...) -> np.ndarray def get_all_coords(data): # type: (np.ndarray) -> np.ndarray return cartesian([list(range(data.shape[i])) for i in range(len(data.shape))]) assert output_size is not None or scale_factors is not None if output_size is not None: scale_factors = np.array(output_size) / np.array(data.shape) else: output_size = (scale_factors * np.array(data.shape)).astype(np.int) assert scale_factors is not None ret = np.zeros(output_size) for x in get_all_coords(ret): ret[tuple(x)] = interpolate_nd_with_x(data, len(data.shape), scale_factors, x, get_coeffs, roi=roi, **kwargs) return ret def cubic_coeffs(ratio, A=-0.75): # type: (float, float) -> np.ndarray coeffs = [((A * (ratio + 1) - 5 * A) * (ratio + 1) + 8 * A) * (ratio + 1) - 4 * A, ((A + 2) * ratio - (A + 3)) * ratio * ratio + 1, ((A + 2) * (1 - ratio) - (A + 3)) * (1 - ratio) * (1 - ratio) + 1, ((A * ((1 - ratio) + 1) - 5 * A) * ((1 - ratio) + 1) + 8 * A) * ((1 - ratio) + 1) - 4 * A] return np.array(coeffs) def linear_coeffs(ratio): # type: (float) -> np.ndarray return np.array([1 - ratio, ratio]) def nearest_coeffs(ratio, mode='round_prefer_floor'): # type: (float, Text) -> np.ndarray if type(ratio) == int or ratio.is_integer(): return np.array([0, 1]) elif mode == 'round_prefer_floor': return np.array([ratio <= 0.5, ratio > 0.5]) elif mode == 'round_prefer_ceil': return np.array([ratio < 0.5, ratio >= 0.5]) elif mode == 'floor': return np.array([1, 0]) elif mode == 'ceil': return np.array([0, 1]) class Resize(Base): @staticmethod def export_resize_upsample_scales_nearest(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='nearest', ) data = np.array([[[ [1, 2], [3, 4], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32) # [[[[1. 1. 1. 2. 2. 2.] # [1. 1. 1. 2. 2. 2.] # [3. 3. 3. 4. 4. 4.] # [3. 3. 3. 4. 4. 4.]]]] output = interpolate_nd( data, nearest_coeffs, scale_factors=scales).astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_upsample_scales_nearest') @staticmethod def export_resize_downsample_scales_nearest(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='nearest', ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32) # [[[[1. 3.]]]] output = interpolate_nd( data, nearest_coeffs, scale_factors=scales).astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_downsample_scales_nearest') @staticmethod def export_resize_upsample_sizes_nearest(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales', 'sizes'], outputs=['Y'], mode='nearest', ) data = np.array([[[ [1, 2], [3, 4], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([], dtype=np.float32) sizes = np.array([1, 1, 7, 8], dtype=np.int64) # [[[[1. 1. 1. 1. 2. 2. 2. 2.] # [1. 1. 1. 1. 2. 2. 2. 2.] # [1. 1. 1. 1. 2. 2. 2. 2.] # [1. 1. 1. 1. 2. 2. 2. 2.] # [3. 3. 3. 3. 4. 4. 4. 4.] # [3. 3. 3. 3. 4. 4. 4. 4.] # [3. 3. 3. 3. 4. 4. 4. 4.]]]] output = interpolate_nd( data, nearest_coeffs, output_size=sizes).astype(np.float32) expect(node, inputs=[data, roi, scales, sizes], outputs=[output], name='test_resize_upsample_sizes_nearest') @staticmethod def export_resize_downsample_sizes_nearest(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales', 'sizes'], outputs=['Y'], mode='nearest', ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([], dtype=np.float32) sizes = np.array([1, 1, 1, 3], dtype=np.int64) # [[[[1. 3.]]]] output = interpolate_nd( data, nearest_coeffs, output_size=sizes).astype(np.float32) expect(node, inputs=[data, roi, scales, sizes], outputs=[output], name='test_resize_downsample_sizes_nearest') @staticmethod def export_resize_upsample_scales_linear(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='linear', ) data = np.array([[[ [1, 2], [3, 4], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32) # [[[[1. 1.25 1.75 2. ] # [1.5 1.75 2.25 2.5 ] # [2.5 2.75 3.25 3.5 ] # [3. 3.25 3.75 4. ]]]] output = interpolate_nd( data, linear_coeffs, scale_factors=scales).astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_upsample_scales_linear') @staticmethod def export_resize_upsample_scales_linear_align_corners(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='linear', coordinate_transformation_mode='align_corners' ) data = np.array([[[ [1, 2], [3, 4], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32) # [[[[1. 1.33333333 1.66666667 2. ] # [1.66666667 2. 2.33333333 2.66666667] # [2.33333333 2.66666667 3. 3.33333333] # [3. 3.33333333 3.66666667 4. ]]]] output = interpolate_nd( data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_upsample_scales_linear_align_corners') @staticmethod def export_resize_downsample_scales_linear(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='linear', ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32) # [[[[2.6666665 4.3333331]]]] output = interpolate_nd( data, linear_coeffs, scale_factors=scales).astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_downsample_scales_linear') @staticmethod def export_resize_downsample_scales_linear_align_corners(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='linear', coordinate_transformation_mode='align_corners' ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32) # [[[[1. 3.142857]]]] output = interpolate_nd( data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_downsample_scales_linear_align_corners') @staticmethod def export_resize_upsample_scales_cubic(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='cubic', ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32) # [[[[ 0.47265625 0.76953125 1.24609375 1.875 2.28125 # 2.91015625 3.38671875 3.68359375] # [ 1.66015625 1.95703125 2.43359375 3.0625 3.46875 # 4.09765625 4.57421875 4.87109375] # [ 3.56640625 3.86328125 4.33984375 4.96875 5.375 # 6.00390625 6.48046875 6.77734375] # [ 6.08203125 6.37890625 6.85546875 7.484375 7.890625 # 8.51953125 8.99609375 9.29296875] # [ 7.70703125 8.00390625 8.48046875 9.109375 9.515625 # 10.14453125 10.62109375 10.91796875] # [10.22265625 10.51953125 10.99609375 11.625 12.03125 # 12.66015625 13.13671875 13.43359375] # [12.12890625 12.42578125 12.90234375 13.53125 13.9375 # 14.56640625 15.04296875 15.33984375] # [13.31640625 13.61328125 14.08984375 14.71875 15.125 # 15.75390625 16.23046875 16.52734375]]]] output = interpolate_nd( data, cubic_coeffs, scale_factors=scales).astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_upsample_scales_cubic') @staticmethod def export_resize_upsample_scales_cubic_align_corners(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='cubic', coordinate_transformation_mode='align_corners' ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32) # [[[[ 1. 1.34110787 1.80029155 2.32944606 2.67055394 # 3.19970845 3.65889213 4. ] # [ 2.36443149 2.70553936 3.16472303 3.69387755 4.03498542 # 4.56413994 5.02332362 5.36443149] # [ 4.20116618 4.54227405 5.00145773 5.53061224 5.87172012 # 6.40087464 6.86005831 7.20116618] # [ 6.31778426 6.65889213 7.1180758 7.64723032 7.98833819 # 8.51749271 8.97667638 9.31778426] # [ 7.68221574 8.02332362 8.48250729 9.01166181 9.35276968 # 9.8819242 10.34110787 10.68221574] # [ 9.79883382 10.13994169 10.59912536 11.12827988 11.46938776 # 11.99854227 12.45772595 12.79883382] # [11.63556851 11.97667638 12.43586006 12.96501458 13.30612245 # 13.83527697 14.29446064 14.63556851] # [13. 13.34110787 13.80029155 14.32944606 14.67055394 # 15.19970845 15.65889213 16. ]]]] output = interpolate_nd( data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_upsample_scales_cubic_align_corners') @staticmethod def export_resize_downsample_scales_cubic(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='cubic', ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32) # [[[[ 1.47119141 2.78125 4.08251953] # [ 6.71142578 8.02148438 9.32275391] # [11.91650391 13.2265625 14.52783203]]]] output = interpolate_nd( data, cubic_coeffs, scale_factors=scales).astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_downsample_scales_cubic') @staticmethod def export_resize_downsample_scales_cubic_align_corners(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='cubic', coordinate_transformation_mode='align_corners' ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32) # [[[[ 1. 2.39519159 3.79038317] # [ 6.58076634 7.97595793 9.37114951] # [12.16153268 13.55672427 14.95191585]]]] output = interpolate_nd( data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_downsample_scales_cubic_align_corners') @staticmethod def export_resize_upsample_sizes_cubic(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales', 'sizes'], outputs=['Y'], mode='cubic', ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([], dtype=np.float32) sizes = np.array([1, 1, 9, 10], dtype=np.int64) # [[[[ 0.45507922 0.64057922 0.97157922 1.42257922 1.90732922 # 2.22332922 2.70807922 3.15907922 3.49007922 3.67557922] # [ 1.39437963 1.57987963 1.91087963 2.36187963 2.84662963 # 3.16262963 3.64737963 4.09837963 4.42937963 4.61487963] # [ 2.95130693 3.13680693 3.46780693 3.91880693 4.40355693 # 4.71955693 5.20430693 5.65530693 5.98630693 6.17180693] # [ 5.20525069 5.39075069 5.72175069 6.17275069 6.65750069 # 6.97350069 7.45825069 7.90925069 8.24025069 8.42575069] # [ 6.88975 7.07525 7.40625 7.85725 8.342 # 8.658 9.14275 9.59375 9.92475 10.11025 ] # [ 8.57424931 8.75974931 9.09074931 9.54174931 10.02649931 # 10.34249931 10.82724931 11.27824931 11.60924931 11.79474931] # [10.82819307 11.01369307 11.34469307 11.79569307 12.28044307 # 12.59644307 13.08119307 13.53219307 13.86319307 14.04869307] # [12.38512037 12.57062037 12.90162037 13.35262037 13.83737037 # 14.15337037 14.63812037 15.08912037 15.42012037 15.60562037] # [13.32442078 13.50992078 13.84092078 14.29192078 14.77667078 # 15.09267078 15.57742078 16.02842078 16.35942078 16.54492078]]]] output = interpolate_nd( data, cubic_coeffs, output_size=sizes).astype(np.float32) expect(node, inputs=[data, roi, scales, sizes], outputs=[output], name='test_resize_upsample_sizes_cubic') @staticmethod def export_resize_downsample_sizes_cubic(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales', 'sizes'], outputs=['Y'], mode='cubic', ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([], dtype=np.float32) sizes = np.array([1, 1, 3, 3], dtype=np.int64) # [[[[ 1.63078704 3.00462963 4.37847222] # [ 7.12615741 8.5 9.87384259] # [12.62152778 13.99537037 15.36921296]]]] output = interpolate_nd( data, cubic_coeffs, output_size=sizes).astype(np.float32) expect(node, inputs=[data, roi, scales, sizes], outputs=[output], name='test_resize_downsample_sizes_cubic') # TensorFlow v1 bicubic with half_pixel_centers=True @staticmethod def export_resize_upsample_scales_cubic_A_n0p5_exclude_outside(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='cubic', cubic_coeff_a=-0.5, exclude_outside=True ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32) # [[[[ 0.55882353 0.81494204 1.35698249 1.89705882 2.39705882 # 2.93713516 3.47917561 3.73529412] # [ 1.58329755 1.83941606 2.38145651 2.92153285 3.42153285 # 3.96160918 4.50364964 4.75976814] # [ 3.75145936 4.00757787 4.54961832 5.08969466 5.58969466 # 6.12977099 6.67181144 6.92792995] # [ 5.91176471 6.16788321 6.70992366 7.25 7.75 # 8.29007634 8.83211679 9.08823529] # [ 7.91176471 8.16788321 8.70992366 9.25 9.75 # 10.29007634 10.83211679 11.08823529] # [10.07207005 10.32818856 10.87022901 11.41030534 11.91030534 # 12.45038168 12.99242213 13.24854064] # [12.24023186 12.49635036 13.03839082 13.57846715 14.07846715 # 14.61854349 15.16058394 15.41670245] # [13.26470588 13.52082439 14.06286484 14.60294118 15.10294118 # 15.64301751 16.18505796 16.44117647]]]] output = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales, exclude_outside=True).astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_upsample_scales_cubic_A_n0p5_exclude_outside') @staticmethod def export_resize_downsample_scales_cubic_A_n0p5_exclude_outside(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='cubic', cubic_coeff_a=-0.5, exclude_outside=True ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32) # [[[[ 1.36812675 2.6695014 4.0133367 ] # [ 6.57362535 7.875 9.2188353 ] # [11.94896657 13.25034122 14.59417652]]]] output = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales, exclude_outside=True).astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_downsample_scales_cubic_A_n0p5_exclude_outside') # TensorFlow v1 bicubic with half_pixel_centers=False @staticmethod def export_resize_upsample_scales_cubic_asymmetric(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales'], outputs=['Y'], mode='cubic', coordinate_transformation_mode='asymmetric' ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) scales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32) roi = np.array([], dtype=np.float32) # [[[[ 1. 1.40625 2. 2.5 3. 3.59375 4. # 4.09375] # [ 2.625 3.03125 3.625 4.125 4.625 5.21875 5.625 # 5.71875] # [ 5. 5.40625 6. 6.5 7. 7.59375 8. # 8.09375] # [ 7. 7.40625 8. 8.5 9. 9.59375 10. # 10.09375] # [ 9. 9.40625 10. 10.5 11. 11.59375 12. # 12.09375] # [11.375 11.78125 12.375 12.875 13.375 13.96875 14.375 # 14.46875] # [13. 13.40625 14. 14.5 15. 15.59375 16. # 16.09375] # [13.375 13.78125 14.375 14.875 15.375 15.96875 16.375 # 16.46875]]]] output = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.75), scale_factors=scales, coordinate_transformation_mode='asymmetric').astype(np.float32) expect(node, inputs=[data, roi, scales], outputs=[output], name='test_resize_upsample_scales_cubic_asymmetric') @staticmethod def export_resize_tf_crop_and_resize(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales', 'sizes'], outputs=['Y'], mode='linear', coordinate_transformation_mode='tf_crop_and_resize' ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) # Note: for some rois, the result may be different with that of TF for inaccurate floating point roi = np.array([0, 0, 0.4, 0.6, 1, 1, 0.6, 0.8], dtype=np.float32) scales = np.array([], dtype=np.float32) sizes = np.array([1, 1, 3, 3], dtype=np.int64) # [[[[ 7.6000004 7.9 8.2 ] # [ 8.8 9.1 9.400001 ] # [10. 10.3 10.6 ]]]] output = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi, coordinate_transformation_mode='tf_crop_and_resize').astype(np.float32) expect(node, inputs=[data, roi, scales, sizes], outputs=[output], name='test_resize_tf_crop_and_resize') @staticmethod def export_resize_tf_crop_and_resize_extrapolation_value(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales', 'sizes'], outputs=['Y'], mode='linear', coordinate_transformation_mode='tf_crop_and_resize', extrapolation_value=10.0 ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) # Note: for some rois, the result may be different with that of TF for inaccurate floating point roi = np.array([0, 0, 0.4, 0.6, 1, 1, 1.2, 1.7], dtype=np.float32) scales = np.array([], dtype=np.float32) sizes = np.array([1, 1, 3, 3], dtype=np.int64) # [[[[ 7.6000004 10. 10. ] # [12.400001 10. 10. ] # [10. 10. 10. ]]]] output = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi, coordinate_transformation_mode='tf_crop_and_resize', extrapolation_value=10.0).astype(np.float32) expect(node, inputs=[data, roi, scales, sizes], outputs=[output], name='test_resize_tf_crop_and_resize') @staticmethod def export_resize_downsample_sizes_nearest_tf_half_pixel_for_nn(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales', 'sizes'], outputs=['Y'], mode='nearest', coordinate_transformation_mode='tf_half_pixel_for_nn' ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([], dtype=np.float32) sizes = np.array([1, 1, 3, 2], dtype=np.int64) # [[[[ 6. 8.] # [10. 12.] # [14. 16.]]]] output = interpolate_nd( data, nearest_coeffs, output_size=sizes, coordinate_transformation_mode='tf_half_pixel_for_nn').astype(np.float32) expect(node, inputs=[data, roi, scales, sizes], outputs=[output], name='test_resize_downsample_sizes_nearest_tf_half_pixel_for_nn') @staticmethod def export_resize_downsample_sizes_linear_pytorch_half_pixel(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales', 'sizes'], outputs=['Y'], mode='linear', coordinate_transformation_mode='pytorch_half_pixel' ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([], dtype=np.float32) sizes = np.array([1, 1, 3, 1], dtype=np.int64) # [[[[ 1.6666666] # [ 7. ] # [12.333333 ]]]] output = interpolate_nd( data, linear_coeffs, output_size=sizes, coordinate_transformation_mode='pytorch_half_pixel').astype(np.float32) expect(node, inputs=[data, roi, scales, sizes], outputs=[output], name='test_resize_downsample_sizes_linear_pytorch_half_pixel') @staticmethod def export_resize_upsample_sizes_nearest_floor_align_corners(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales', 'sizes'], outputs=['Y'], mode='nearest', coordinate_transformation_mode='align_corners', nearest_mode='floor' ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([], dtype=np.float32) sizes = np.array([1, 1, 8, 8], dtype=np.int64) # [[[[ 1. 1. 1. 2. 2. 3. 3. 4.] # [ 1. 1. 1. 2. 2. 3. 3. 4.] # [ 1. 1. 1. 2. 2. 3. 3. 4.] # [ 5. 5. 5. 6. 6. 7. 7. 8.] # [ 5. 5. 5. 6. 6. 7. 7. 8.] # [ 9. 9. 9. 10. 10. 11. 11. 12.] # [ 9. 9. 9. 10. 10. 11. 11. 12.] # [13. 13. 13. 14. 14. 15. 15. 16.]]]] output = interpolate_nd( data, lambda x: nearest_coeffs(x, mode='floor'), output_size=sizes, coordinate_transformation_mode='align_corners').astype(np.float32) expect(node, inputs=[data, roi, scales, sizes], outputs=[output], name='test_resize_upsample_sizes_nearest_floor_align_corners') @staticmethod def export_resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales', 'sizes'], outputs=['Y'], mode='nearest', coordinate_transformation_mode='asymmetric', nearest_mode='round_prefer_ceil' ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([], dtype=np.float32) sizes = np.array([1, 1, 8, 8], dtype=np.int64) # [[[[ 1. 2. 2. 3. 3. 4. 4. 4.] # [ 5. 6. 6. 7. 7. 8. 8. 8.] # [ 5. 6. 6. 7. 7. 8. 8. 8.] # [ 9. 10. 10. 11. 11. 12. 12. 12.] # [ 9. 10. 10. 11. 11. 12. 12. 12.] # [13. 14. 14. 15. 15. 16. 16. 16.] # [13. 14. 14. 15. 15. 16. 16. 16.] # [13. 14. 14. 15. 15. 16. 16. 16.]]]] output = interpolate_nd( data, lambda x: nearest_coeffs(x, mode='round_prefer_ceil'), output_size=sizes, coordinate_transformation_mode='asymmetric').astype(np.float32) expect(node, inputs=[data, roi, scales, sizes], outputs=[output], name='test_resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric') @staticmethod def export_resize_upsample_sizes_nearest_ceil_half_pixel(): # type: () -> None node = onnx.helper.make_node( 'Resize', inputs=['X', 'roi', 'scales', 'sizes'], outputs=['Y'], mode='nearest', coordinate_transformation_mode='half_pixel', nearest_mode='ceil' ) data = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]], dtype=np.float32) roi = np.array([], dtype=np.float32) scales = np.array([], dtype=np.float32) sizes = np.array([1, 1, 8, 8], dtype=np.int64) # [[[[ 1. 2. 2. 3. 3. 4. 4. 4.] # [ 5. 6. 6. 7. 7. 8. 8. 8.] # [ 5. 6. 6. 7. 7. 8. 8. 8.] # [ 9. 10. 10. 11. 11. 12. 12. 12.] # [ 9. 10. 10. 11. 11. 12. 12. 12.] # [13. 14. 14. 15. 15. 16. 16. 16.] # [13. 14. 14. 15. 15. 16. 16. 16.] # [13. 14. 14. 15. 15. 16. 16. 16.]]]] output = interpolate_nd( data, lambda x: nearest_coeffs(x, mode='ceil'), output_size=sizes).astype(np.float32) expect(node, inputs=[data, roi, scales, sizes], outputs=[output], name='test_resize_upsample_sizes_nearest_ceil_half_pixel')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Round(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Round', inputs=['x'], outputs=['y'], ) x = np.array([0.1, 0.5, 0.9, 1.2, 1.5, 1.8, 2.3, 2.5, 2.7, -1.1, -1.5, -1.9, -2.2, -2.5, -2.8]).astype(np.float32) y = np.array([0., 0., 1., 1., 2., 2., 2., 2., 3., -1., -2., -2., -2., -2., -3.]).astype(np.float32) # expected output expect(node, inputs=[x], outputs=[y], name='test_round')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import itertools import onnx from ..base import Base from . import expect class Transpose(Base): @staticmethod def export_default(): # type: () -> None shape = (2, 3, 4) data = np.random.random_sample(shape).astype(np.float32) node = onnx.helper.make_node( 'Transpose', inputs=['data'], outputs=['transposed'] ) transposed = np.transpose(data) expect(node, inputs=[data], outputs=[transposed], name='test_transpose_default') @staticmethod def export_all_permutations(): # type: () -> None shape = (2, 3, 4) data = np.random.random_sample(shape).astype(np.float32) permutations = list(itertools.permutations(np.arange(len(shape)))) for i in range(len(permutations)): node = onnx.helper.make_node( 'Transpose', inputs=['data'], outputs=['transposed'], perm=permutations[i] ) transposed = np.transpose(data, permutations[i]) expect(node, inputs=[data], outputs=[transposed], name='test_transpose_all_permutations_' + str(i))
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect def compute_negative_log_likelihood_loss(input, target, weight=None, reduction='mean', ignore_index=None): # type: ignore input_shape = input.shape if len(input_shape) == 1: raise RuntimeError("Unsupported shape") target_shape = target.shape N = input_shape[0] C = input_shape[1] # initialize the positional weights when required gather_weight = None if weight is not None: # setting mode='clip' to deal with ignore_index > C or < 0 cases. # when the target value is > C or < 0, it doesn't matter which value we are # taking in gather_weight, since it will be set to 0 in the following if-block gather_weight = np.take(weight, target, mode='clip') # set `ignore_index`'s loss weight to 0. # The loss tensor will be multiplied by this weight tensor, # so `ingore_index`'s loss value will be eliminated. if ignore_index is not None: gather_weight = np.where(target == ignore_index, 0, gather_weight).astype(dtype=np.float32) elif ignore_index is not None: gather_weight = np.where(target == ignore_index, 0, 1).astype(dtype=np.float32) # if input is 4-d and above, make it 3-d if len(input_shape) != 3: input = input.reshape((N, C, -1)) target = target.reshape((N, -1)) # Get a dimension from the reshaped input. # If the original input shape is [N, C, H, W], # the D here should be H * W because we reshape # [N, C, H, W] to [N, C, H * W]. D = input.shape[2] neg_gather_element_input = np.zeros((N, D), dtype=np.float32) for i in range(N): for d in range(D): if target[i][d] != ignore_index: neg_gather_element_input[i][d] = -input[i][target[i][d]][d] loss = neg_gather_element_input # if the input was 4-d or above reshape to the right shape if len(input_shape) != 3: loss = loss.reshape(target_shape) # apply the weights when required if gather_weight is not None: loss = gather_weight * loss if reduction == 'mean': loss = loss.sum() / gather_weight.sum() return loss if reduction == 'mean': loss = np.mean(loss) elif reduction == 'sum': loss = np.sum(loss) return loss class NegativeLogLikelihoodLoss(Base): @staticmethod def export_input_shape_is_NC(): # type: () -> None reduction = 'none' node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target'], outputs=['loss'], reduction=reduction ) N, C = 3, 5 np.random.seed(0) input = np.random.rand(N, C).astype(np.float32) target = np.random.randint(0, high=C, size=(N, )) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction) expect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NC') @staticmethod def export_input_shape_is_NCd1d2(): # type: () -> None reduction = 'none' node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target'], outputs=['loss'], reduction=reduction ) N, C, dim1, dim2 = 3, 5, 6, 6 np.random.seed(0) input = np.random.rand(N, C, dim1, dim2).astype(np.float32) target = np.random.randint(0, high=C, size=(N, dim1, dim2)) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction) expect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1d2') @staticmethod def export_input_shape_is_NCd1d2_reduction_mean(): # type: () -> None reduction = 'mean' node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target'], outputs=['loss'], reduction=reduction ) N, C, dim1, dim2 = 3, 5, 6, 6 np.random.seed(0) input = np.random.rand(N, C, dim1, dim2).astype(np.float32) target = np.random.randint(0, high=C, size=(N, dim1, dim2)) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction) expect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1d2_reduction_mean') @staticmethod def export_input_shape_is_NCd1d2_reduction_sum(): # type: () -> None reduction = 'sum' node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target'], outputs=['loss'], reduction=reduction ) N, C, dim1, dim2 = 3, 5, 6, 6 np.random.seed(0) input = np.random.rand(N, C, dim1, dim2).astype(np.float32) target = np.random.randint(0, high=C, size=(N, dim1, dim2)) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction) expect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1d2_reduction_sum') @staticmethod def export_input_shape_is_NCd1d2_with_weight(): # type: () -> None reduction = 'none' node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target', 'weight'], outputs=['loss'], reduction=reduction ) N, C, dim1, dim2 = 3, 5, 6, 6 np.random.seed(0) input = np.random.rand(N, C, dim1, dim2).astype(np.float32) target = np.random.randint(0, high=C, size=(N, dim1, dim2)) weight = np.random.rand(C).astype(np.float32) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction) expect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1d2_with_weight') @staticmethod def export_input_shape_is_NCd1d2_with_weight_reduction_mean(): # type: () -> None reduction = 'mean' node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target', 'weight'], outputs=['loss'], reduction=reduction ) N, C, dim1, dim2 = 3, 5, 6, 6 np.random.seed(0) input = np.random.rand(N, C, dim1, dim2).astype(np.float32) target = np.random.randint(0, high=C, size=(N, dim1, dim2)) weight = np.random.rand(C).astype(np.float32) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction) expect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1d2_with_weight_reduction_mean') @staticmethod def export_input_shape_is_NCd1d2_with_weight_reduction_sum(): # type: () -> None reduction = 'sum' node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target', 'weight'], outputs=['loss'], reduction=reduction ) N, C, dim1, dim2 = 3, 5, 6, 6 np.random.seed(0) input = np.random.rand(N, C, dim1, dim2).astype(np.float32) target = np.random.randint(0, high=C, size=(N, dim1, dim2)) weight = np.random.rand(C).astype(np.float32) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction) expect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1d2_with_weight_reduction_sum') @staticmethod def export_input_shape_is_NCd1d2_with_weight_reduction_sum_ignore_index(): # type: () -> None reduction = 'sum' ignore_index = np.int64(0) node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target', 'weight'], outputs=['loss'], reduction=reduction, ignore_index=ignore_index ) N, C, dim1, dim2 = 3, 5, 6, 6 np.random.seed(0) input = np.random.rand(N, C, dim1, dim2).astype(np.float32) target = np.random.randint(0, high=C, size=(N, dim1, dim2)) target[0][0][0] = np.int64(0) weight = np.random.rand(C).astype(np.float32) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction, ignore_index=ignore_index) expect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1d2_with_weight_reduction_sum_ignore_index') @staticmethod def export_input_shape_is_NCd1d2_no_weight_reduction_mean_ignore_index(): # type: () -> None reduction = 'mean' ignore_index = np.int64(1) node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target'], outputs=['loss'], reduction=reduction, ignore_index=ignore_index ) N, C, dim1, dim2 = 3, 5, 6, 6 np.random.seed(0) input = np.random.rand(N, C, dim1, dim2).astype(np.float32) target = np.random.randint(0, high=C, size=(N, dim1, dim2)) target[0][0][0] = np.int64(1) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, reduction=reduction, ignore_index=ignore_index) expect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1d2_no_weight_reduction_mean_ignore_index') @staticmethod def export_input_shape_is_NCd1(): # type: () -> None reduction = 'mean' node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target'], outputs=['loss'], reduction=reduction ) N, C, d1 = 3, 5, 2 np.random.seed(0) input = np.random.rand(N, C, d1).astype(np.float32) target = np.random.randint(0, high=C, size=(N, d1)) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction) expect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1') @staticmethod def export_input_shape_is_NCd1_weight(): # type: () -> None reduction = 'mean' node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target', 'weight'], outputs=['loss'], reduction=reduction ) N, C, d1 = 3, 5, 2 np.random.seed(0) input = np.random.rand(N, C, d1).astype(np.float32) target = np.random.randint(0, high=C, size=(N, d1)) weight = np.random.rand(C).astype(np.float32) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction) expect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1_weight') @staticmethod def export_input_shape_is_NCd1_ignore_index(): # type: () -> None reduction = 'mean' ignore_index = np.int64(1) node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target'], outputs=['loss'], reduction=reduction, ignore_index=ignore_index ) N, C, d1 = 3, 5, 2 np.random.seed(0) input = np.random.rand(N, C, d1).astype(np.float32) target = np.random.randint(0, high=C, size=(N, d1)) target[0][0] = np.int64(1) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction, ignore_index=ignore_index) expect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1_ignore_index') @staticmethod def export_input_shape_is_NCd1_weight_ignore_index(): # type: () -> None reduction = 'mean' ignore_index = np.int64(1) node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target', 'weight'], outputs=['loss'], reduction=reduction, ignore_index=ignore_index ) N, C, d1 = 3, 5, 2 np.random.seed(0) input = np.random.rand(N, C, d1).astype(np.float32) target = np.random.randint(0, high=C, size=(N, d1)) target[0][0] = np.int64(1) weight = np.random.rand(C).astype(np.float32) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction, ignore_index=ignore_index) expect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_iinput_shape_is_NCd1_weight_ignore_index') @staticmethod def export_input_shape_is_NCd1d2d3d4d5_mean_weight(): # type: () -> None reduction = 'mean' node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target', 'weight'], outputs=['loss'], reduction=reduction) N, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4 np.random.seed(0) input = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32) target = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5)) weight = np.random.rand(C).astype(np.float32) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction) expect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1d2d3d4d5_mean_weight') @staticmethod def export_input_shape_is_NCd1d2d3d4d5_none_no_weight(): # type: () -> None reduction = 'none' node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target'], outputs=['loss'], reduction=reduction) N, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4 np.random.seed(0) input = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32) target = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5)) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, reduction=reduction) expect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1d2d3d4d5_none_no_weight') @staticmethod def export_input_shape_is_NCd1_mean_weight_negative_ignore_index(): # type: () -> None reduction = 'mean' ignore_index = np.int64(-1) node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target', 'weight'], outputs=['loss'], reduction=reduction, ignore_index=ignore_index) N, C, dim1 = 3, 5, 6 np.random.seed(0) input = np.random.rand(N, C, dim1).astype(np.float32) target = np.random.randint(0, high=C, size=(N, dim1)) target[0][0] = -1 weight = np.random.rand(C).astype(np.float32) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction, ignore_index=ignore_index) expect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1_mean_weight_negative_ignore_index') @staticmethod def export_input_shape_is_NCd1d2d3_none_no_weight_negative_ignore_index(): # type: () -> None reduction = 'none' ignore_index = np.int64(-5) node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target'], outputs=['loss'], reduction=reduction, ignore_index=ignore_index) N, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5 np.random.seed(0) input = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32) target = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3)) target[0][0][0][0] = -5 negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, reduction=reduction, ignore_index=ignore_index) expect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1d2d3_none_no_weight_negative_ignore_index') @staticmethod def export_input_shape_is_NCd1d2d3_sum_weight_high_ignore_index(): # type: () -> None reduction = 'sum' ignore_index = np.int64(10) node = onnx.helper.make_node( 'NegativeLogLikelihoodLoss', inputs=['input', 'target', 'weight'], outputs=['loss'], reduction=reduction, ignore_index=ignore_index) N, C = 3, 5 np.random.seed(0) input = np.random.rand(N, C).astype(np.float32) target = np.random.randint(0, high=C, size=(N)) target[0] = 10 weight = np.random.rand(C).astype(np.float32) negative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction, ignore_index=ignore_index) expect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss], name='test_negative_log_likelihood_loss_input_shape_is_NCd1d2d3_sum_weight_high_ignore_index')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from onnx import TensorProto from ..base import Base from . import expect class DynamicQuantizeLinear(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node('DynamicQuantizeLinear', inputs=['x'], outputs=['y', 'y_scale', 'y_zero_point'], ) # expected scale 0.0196078438 and zero point 153 X = np.array([0, 2, -3, -2.5, 1.34, 0.5]).astype(np.float32) x_min = np.minimum(0, np.min(X)) x_max = np.maximum(0, np.max(X)) Y_Scale = np.float32((x_max - x_min) / (255 - 0)) # uint8 -> [0, 255] Y_ZeroPoint = np.clip(round((0 - x_min) / Y_Scale), 0, 255).astype(np.uint8) Y = np.clip(np.round(X / Y_Scale) + Y_ZeroPoint, 0, 255).astype(np.uint8) expect(node, inputs=[X], outputs=[Y, Y_Scale, Y_ZeroPoint], name='test_dynamicquantizelinear') # expected scale 0.0156862754 and zero point 255 X = np.array([-1.0, -2.1, -1.3, -2.5, -3.34, -4.0]).astype(np.float32) x_min = np.minimum(0, np.min(X)) x_max = np.maximum(0, np.max(X)) Y_Scale = np.float32((x_max - x_min) / (255 - 0)) # uint8 -> [0, 255] Y_ZeroPoint = np.clip(round((0 - x_min) / Y_Scale), 0, 255).astype(np.uint8) Y = np.clip(np.round(X / Y_Scale) + Y_ZeroPoint, 0, 255).astype(np.uint8) expect(node, inputs=[X], outputs=[Y, Y_Scale, Y_ZeroPoint], name='test_dynamicquantizelinear_max_adjusted') X = np.array([1, 2.1, 1.3, 2.5, 3.34, 4.0, 1.5, 2.6, 3.9, 4.0, 3.0, 2.345]).astype(np.float32).reshape((3, 4)) # expected scale 0.0156862754 and zero point 0 x_min = np.minimum(0, np.min(X)) x_max = np.maximum(0, np.max(X)) Y_Scale = np.float32((x_max - x_min) / (255 - 0)) # uint8 -> [0, 255] Y_ZeroPoint = np.clip(round((0 - x_min) / Y_Scale), 0, 255).astype(np.uint8) Y = np.clip(np.round(X / Y_Scale) + Y_ZeroPoint, 0, 255).astype(np.uint8) expect(node, inputs=[X], outputs=[Y, Y_Scale, Y_ZeroPoint], name='test_dynamicquantizelinear_min_adjusted')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Split(Base): @staticmethod def export_1d(): # type: () -> None input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32) node = onnx.helper.make_node( 'Split', inputs=['input'], outputs=['output_1', 'output_2', 'output_3'], axis=0 ) expected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)] expect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_1d') node = onnx.helper.make_node( 'Split', inputs=['input'], outputs=['output_1', 'output_2'], axis=0, split=[2, 4] ) expected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)] expect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_1d') @staticmethod def export_2d(): # type: () -> None input = np.array([[1., 2., 3., 4., 5., 6.], [7., 8., 9., 10., 11., 12.]]).astype(np.float32) node = onnx.helper.make_node( 'Split', inputs=['input'], outputs=['output_1', 'output_2'], axis=1 ) expected_outputs = [np.array([[1., 2., 3.], [7., 8., 9.]]).astype(np.float32), np.array([[4., 5., 6.], [10., 11., 12.]]).astype(np.float32)] expect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_2d') node = onnx.helper.make_node( 'Split', inputs=['input'], outputs=['output_1', 'output_2'], axis=1, split=[2, 4] ) expected_outputs = [np.array([[1., 2.], [7., 8.]]).astype(np.float32), np.array([[3., 4., 5., 6.], [9., 10., 11., 12.]]).astype(np.float32)] expect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_2d') @staticmethod def export_default_values(): # type: () -> None input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32) # If axis is not specified, split is applied on default axis 0 node = onnx.helper.make_node( 'Split', inputs=['input'], outputs=['output_1', 'output_2', 'output_3'] ) expected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)] expect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_default_axis') node = onnx.helper.make_node( 'Split', inputs=['input'], outputs=['output_1', 'output_2'], split=[2, 4] ) expected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)] expect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_default_axis') @staticmethod def export_zero_size_splits(): # type: () -> None input = np.array([]).astype(np.float32) # Split emtpy tensor to tensors of size zero node = onnx.helper.make_node( 'Split', inputs=['input'], outputs=['output_1', 'output_2', 'output_3'], split=[0, 0, 0] ) expected_outputs = [np.array([]).astype(np.float32), np.array([]).astype(np.float32), np.array([]).astype(np.float32)] expect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_zero_size_splits')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class PRelu(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'PRelu', inputs=['x', 'slope'], outputs=['y'], ) x = np.random.randn(3, 4, 5).astype(np.float32) slope = np.random.randn(3, 4, 5).astype(np.float32) y = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope expect(node, inputs=[x, slope], outputs=[y], name='test_prelu_example') @staticmethod def export_prelu_broadcast(): # type: () -> None node = onnx.helper.make_node( 'PRelu', inputs=['x', 'slope'], outputs=['y'], ) x = np.random.randn(3, 4, 5).astype(np.float32) slope = np.random.randn(5).astype(np.float32) y = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope expect(node, inputs=[x, slope], outputs=[y], name='test_prelu_broadcast')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class GlobalAveragePool(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'GlobalAveragePool', inputs=['x'], outputs=['y'], ) x = np.random.randn(1, 3, 5, 5).astype(np.float32) spatial_shape = np.ndim(x) - 2 y = np.average(x, axis=tuple(range(spatial_shape, spatial_shape + 2))) for _ in range(spatial_shape): y = np.expand_dims(y, -1) expect(node, inputs=[x], outputs=[y], name='test_globalaveragepool') @staticmethod def export_globalaveragepool_precomputed(): # type: () -> None node = onnx.helper.make_node( 'GlobalAveragePool', inputs=['x'], outputs=['y'], ) x = np.array([[[ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]]]).astype(np.float32) y = np.array([[[[5]]]]).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_globalaveragepool_precomputed')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect from .pool_op_common import get_output_shape, get_pad_shape, pool class MaxPool(Base): @staticmethod def export_maxpool_2d_uint8(): # type: () -> None """ input_shape: [1, 1, 5, 5] output_shape: [1, 1, 5, 5] pad_shape: [4, 4] -> [2, 2, 2, 2] by axis """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[5, 5], pads=[2, 2, 2, 2] ) x = np.array([[[ [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], ]]]).astype(np.uint8) y = np.array([[[ [13, 14, 15, 15, 15], [18, 19, 20, 20, 20], [23, 24, 25, 25, 25], [23, 24, 25, 25, 25], [23, 24, 25, 25, 25]]]]).astype(np.uint8) expect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_uint8') @staticmethod def export_maxpool_2d_precomputed_pads(): # type: () -> None """ input_shape: [1, 1, 5, 5] output_shape: [1, 1, 5, 5] pad_shape: [4, 4] -> [2, 2, 2, 2] by axis """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[5, 5], pads=[2, 2, 2, 2] ) x = np.array([[[ [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], ]]]).astype(np.float32) y = np.array([[[ [13, 14, 15, 15, 15], [18, 19, 20, 20, 20], [23, 24, 25, 25, 25], [23, 24, 25, 25, 25], [23, 24, 25, 25, 25]]]]).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_pads') @staticmethod def export_maxpool_with_argmax_2d_precomputed_pads(): # type: () -> None """ input_shape: [1, 1, 5, 5] output_shape: [1, 1, 5, 5] pad_shape: [4, 4] -> [2, 2, 2, 2] by axis """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y', 'z'], kernel_shape=[5, 5], pads=[2, 2, 2, 2] ) x = np.array([[[ [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], ]]]).astype(np.float32) y = np.array([[[ [13, 14, 15, 15, 15], [18, 19, 20, 20, 20], [23, 24, 25, 25, 25], [23, 24, 25, 25, 25], [23, 24, 25, 25, 25]]]]).astype(np.float32) z = np.array([[[ [12, 13, 14, 14, 14], [17, 18, 19, 19, 19], [22, 23, 24, 24, 24], [22, 23, 24, 24, 24], [22, 23, 24, 24, 24]]]]).astype(np.int64) expect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_pads') @staticmethod def export_maxpool_2d_precomputed_strides(): # type: () -> None """ input_shape: [1, 1, 5, 5] output_shape: [1, 1, 2, 2] """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[2, 2], strides=[2, 2] ) x = np.array([[[ [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], ]]]).astype(np.float32) y = np.array([[[[7, 9], [17, 19]]]]).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_strides') @staticmethod def export_maxpool_with_argmax_2d_precomputed_strides(): # type: () -> None """ input_shape: [1, 1, 5, 5] output_shape: [1, 1, 2, 2] """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y', 'z'], kernel_shape=[2, 2], strides=[2, 2], storage_order=1 ) x = np.array([[[ [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], ]]]).astype(np.float32) y = np.array([[[[7, 9], [17, 19]]]]).astype(np.float32) z = np.array([[[[6, 16], [8, 18]]]]).astype(np.int64) expect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_strides') @staticmethod def export_maxpool_2d_precomputed_same_upper(): # type: () -> None """ input_shape: [1, 1, 5, 5] output_shape: [1, 1, 3, 3] pad_shape: [2, 2] -> [1, 1, 1, 1] by axis """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[3, 3], strides=[2, 2], auto_pad='SAME_UPPER' ) x = np.array([[[ [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], ]]]).astype(np.float32) y = np.array([[[[7, 9, 10], [17, 19, 20], [22, 24, 25]]]]).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_same_upper') @staticmethod def export_maxpool_1d_default(): # type: () -> None """ input_shape: [1, 3, 32] output_shape: [1, 3, 31] """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[2], ) x = np.random.randn(1, 3, 32).astype(np.float32) x_shape = np.shape(x) kernel_shape = [2] strides = [1] out_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides) padded = x y = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'MAX') expect(node, inputs=[x], outputs=[y], name='test_maxpool_1d_default') @staticmethod def export_maxpool_2d_default(): # type: () -> None """ input_shape: [1, 3, 32, 32] output_shape: [1, 3, 31, 31] """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[2, 2], ) x = np.random.randn(1, 3, 32, 32).astype(np.float32) x_shape = np.shape(x) kernel_shape = (2, 2) strides = (1, 1) out_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides) padded = x y = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX') expect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_default') @staticmethod def export_maxpool_3d_default(): # type: () -> None """ input_shape: [1, 3, 32, 32, 32] output_shape: [1, 3, 31, 31, 31] """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[2, 2, 2], ) x = np.random.randn(1, 3, 32, 32, 32).astype(np.float32) x_shape = np.shape(x) kernel_shape = [2, 2, 2] strides = [1, 1, 1] out_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides) padded = x y = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'MAX') expect(node, inputs=[x], outputs=[y], name='test_maxpool_3d_default') @staticmethod def export_maxpool_2d_same_upper(): # type: () -> None """ input_shape: [1, 3, 32, 32] output_shape: [1, 3, 32, 32] pad_shape: [1, 1] -> [0, 1, 0, 1] by axis """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[2, 2], auto_pad='SAME_UPPER' ) x = np.random.randn(1, 3, 32, 32).astype(np.float32) x_shape = np.shape(x) kernel_shape = (2, 2) strides = (1, 1) out_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides) pad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape) pad_top = pad_shape[0] // 2 pad_bottom = pad_shape[0] - pad_top pad_left = pad_shape[1] // 2 pad_right = pad_shape[1] - pad_left padded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant', constant_values=np.nan) y = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX') expect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_upper') @staticmethod def export_maxpool_2d_same_lower(): # type: () -> None """ input_shape: [1, 3, 32, 32] output_shape: [1, 3, 32, 32] pad_shape: [1, 1] -> [1, 0, 1, 0] by axis """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[2, 2], auto_pad='SAME_LOWER' ) x = np.random.randn(1, 3, 32, 32).astype(np.float32) x_shape = np.shape(x) kernel_shape = (2, 2) strides = (1, 1) out_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides) pad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape) pad_bottom = pad_shape[0] // 2 pad_top = pad_shape[0] - pad_bottom pad_right = pad_shape[1] // 2 pad_left = pad_shape[1] - pad_right padded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant', constant_values=np.nan) y = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX') expect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_lower') @staticmethod def export_maxpool_2d_pads(): # type: () -> None """ input_shape: [1, 3, 28, 28] output_shape: [1, 3, 30, 30] pad_shape: [4, 4] -> [2, 2, 2, 2] by axis """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[3, 3], pads=[2, 2, 2, 2] ) x = np.random.randn(1, 3, 28, 28).astype(np.float32) x_shape = np.shape(x) kernel_shape = (3, 3) strides = (1, 1) pad_bottom = pad_top = pad_right = pad_left = 2 pad_shape = [pad_top + pad_bottom, pad_left + pad_right] out_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides) padded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant', constant_values=np.nan) y = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX') expect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_pads') @staticmethod def export_maxpool_2d_strides(): # type: () -> None """ input_shape: [1, 3, 32, 32] output_shape: [1, 3, 10, 10] """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[5, 5], strides=[3, 3] ) x = np.random.randn(1, 3, 32, 32).astype(np.float32) x_shape = np.shape(x) kernel_shape = (5, 5) strides = (3, 3) out_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides) padded = x y = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX') expect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_strides') @staticmethod def export_maxpool_2d_ceil(): # type: () -> None """ input_shape: [1, 1, 4, 4] output_shape: [1, 1, 2, 2] """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[3, 3], strides=[2, 2], ceil_mode=True ) x = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]]).astype(np.float32) y = np.array([[[ [11, 12], [15, 16]]]]).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_ceil') @staticmethod def export_maxpool_2d_dilations(): # type: () -> None """ input_shape: [1, 1, 4, 4] output_shape: [1, 1, 2, 2] """ node = onnx.helper.make_node( 'MaxPool', inputs=['x'], outputs=['y'], kernel_shape=[2, 2], strides=[1, 1], dilations=[2, 2] ) x = np.array([[[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]]]).astype(np.float32) y = np.array([[[ [11, 12], [15, 16]]]]).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_dilations')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class MaxUnpool(Base): @staticmethod def export_without_output_shape(): # type: () -> None node = onnx.helper.make_node( 'MaxUnpool', inputs=['xT', 'xI'], outputs=['y'], kernel_shape=[2, 2], strides=[2, 2] ) xT = np.array([[[[1, 2], [3, 4]]]], dtype=np.float32) xI = np.array([[[[5, 7], [13, 15]]]], dtype=np.int64) y = np.array([[[[0, 0, 0, 0], [0, 1, 0, 2], [0, 0, 0, 0], [0, 3, 0, 4]]]], dtype=np.float32) expect(node, inputs=[xT, xI], outputs=[y], name='test_maxunpool_export_without_output_shape') @staticmethod def export_with_output_shape(): # type: () -> None node = onnx.helper.make_node( 'MaxUnpool', inputs=['xT', 'xI', 'output_shape'], outputs=['y'], kernel_shape=[2, 2], strides=[2, 2] ) xT = np.array([[[[5, 6], [7, 8]]]], dtype=np.float32) xI = np.array([[[[5, 7], [13, 15]]]], dtype=np.int64) output_shape = np.array((1, 1, 5, 5), dtype=np.int64) y = np.array([[[[0, 0, 0, 0, 0], [0, 5, 0, 6, 0], [0, 0, 0, 0, 0], [0, 7, 0, 8, 0], [0, 0, 0, 0, 0]]]], dtype=np.float32) expect(node, inputs=[xT, xI, output_shape], outputs=[y], name='test_maxunpool_export_with_output_shape')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class EyeLike(Base): @staticmethod def export_without_dtype(): # type: () -> None shape = (4, 4) node = onnx.helper.make_node( 'EyeLike', inputs=['x'], outputs=['y'], ) x = np.random.randint(0, 100, size=shape, dtype=np.int32) y = np.eye(shape[0], shape[1], dtype=np.int32) expect(node, inputs=[x], outputs=[y], name='test_eyelike_without_dtype') @staticmethod def export_with_dtype(): # type: () -> None shape = (3, 4) node = onnx.helper.make_node( 'EyeLike', inputs=['x'], outputs=['y'], dtype=onnx.TensorProto.DOUBLE, ) x = np.random.randint(0, 100, size=shape, dtype=np.int32) y = np.eye(shape[0], shape[1], dtype=np.float64) expect(node, inputs=[x], outputs=[y], name='test_eyelike_with_dtype') @staticmethod def export_populate_off_main_diagonal(): # type: () -> None shape = (4, 5) off_diagonal_offset = 1 node = onnx.helper.make_node( 'EyeLike', inputs=['x'], outputs=['y'], k=off_diagonal_offset, dtype=onnx.TensorProto.FLOAT, ) x = np.random.randint(0, 100, size=shape, dtype=np.int32) y = np.eye(shape[0], shape[1], k=off_diagonal_offset, dtype=np.float32) expect(node, inputs=[x], outputs=[y], name='test_eyelike_populate_off_main_diagonal')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect def gather_nd_impl(data, indices, batch_dims): # type: (np.ndarray, np.ndarray, int) -> np.ndarray # Note the data rank - will be reused multiple times later data_rank = len(data.shape) # Check input tensors' shape/rank condition assert indices.shape[-1] <= data_rank #The list of data/indice shape of batch_dims batch_dims_shape = [] #The number of elements in the batch_dims for data/indice array batch_dims_size = 1 # Check the shape of indice and data are identicial for batch dims. for i in range(batch_dims): batch_dims_shape.append(indices.shape[i]) batch_dims_size *= indices.shape[i] # Compute output of the op as below # Compute shape of output array output_shape = batch_dims_shape + list(indices.shape)[batch_dims:-1] if (indices.shape[-1] == data_rank - batch_dims) \ else batch_dims_shape + list(indices.shape)[batch_dims:-1] + list(data.shape)[batch_dims + indices.shape[-1]:] # Placeholder for output data output_data_buffer = [] # Flatten 'indices' to 2D array reshaped_indices = indices.reshape(batch_dims_size, -1, indices.shape[-1]) # Flatten 'data' to array of shape (batch_dim_size, data.shape[batch_dimes:]) reshaped_data = data.reshape((batch_dims_size, ) + data.shape[batch_dims:]) # gather each scalar value from 'data' for batch_dim in range(reshaped_indices.shape[0]): for outer_dim in range(reshaped_indices.shape[1]): gather_index = tuple(reshaped_indices[batch_dim][outer_dim]) output_data_buffer.append(reshaped_data[(batch_dim,) + gather_index]) return np.asarray(output_data_buffer, dtype=data.dtype).reshape(output_shape) class GatherND(Base): @staticmethod def export_int32(): # type: () -> None node = onnx.helper.make_node( 'GatherND', inputs=['data', 'indices'], outputs=['output'], ) data = np.array([[0, 1], [2, 3]], dtype=np.int32) indices = np.array([[0, 0], [1, 1]], dtype=np.int64) output = gather_nd_impl(data, indices, 0) expected_output = np.array([0, 3], dtype=np.int32) assert (np.array_equal(output, expected_output)) expect(node, inputs=[data, indices], outputs=[output], name='test_gathernd_example_int32') @staticmethod def export_float32(): # type: () -> None node = onnx.helper.make_node( 'GatherND', inputs=['data', 'indices'], outputs=['output'], ) data = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.float32) indices = np.array([[[0, 1]], [[1, 0]]], dtype=np.int64) output = gather_nd_impl(data, indices, 0) expected_output = np.array([[[2, 3]], [[4, 5]]], dtype=np.float32) assert (np.array_equal(output, expected_output)) expect(node, inputs=[data, indices], outputs=[output], name='test_gathernd_example_float32') @staticmethod def export_int32_batchdim_1(): # type: () -> None node = onnx.helper.make_node( 'GatherND', inputs=['data', 'indices'], outputs=['output'], batch_dims=1, ) data = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.int32) indices = np.array([[1], [0]], dtype=np.int64) output = gather_nd_impl(data, indices, 1) expected_output = np.array([[2, 3], [4, 5]], dtype=np.int32) assert (np.array_equal(output, expected_output)) expect(node, inputs=[data, indices], outputs=[output], name='test_gathernd_example_int32_batch_dim1')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect from onnx import helper # The below Scatter's numpy implementation is from https://stackoverflow.com/a/46204790/11767360 def scatter(data, indices, updates, axis=0): # type: ignore if axis < 0: axis = data.ndim + axis idx_xsection_shape = indices.shape[:axis] + indices.shape[axis + 1:] def make_slice(arr, axis, i): # type: ignore slc = [slice(None)] * arr.ndim slc[axis] = i return slc def unpack(packed): # type: ignore unpacked = packed[0] for i in range(1, len(packed)): unpacked = unpacked, packed[i] return unpacked # We use indices and axis parameters to create idx # idx is in a form that can be used as a NumPy advanced indices for scattering of updates param. in data idx = [[unpack(np.indices(idx_xsection_shape).reshape(indices.ndim - 1, -1)), indices[tuple(make_slice(indices, axis, i))].reshape(1, -1)[0]] for i in range(indices.shape[axis])] idx = list(np.concatenate(idx, axis=1)) idx.insert(axis, idx.pop()) # updates_idx is a NumPy advanced indices for indexing of elements in the updates updates_idx = list(idx) updates_idx.pop(axis) updates_idx.insert(axis, np.repeat(np.arange(indices.shape[axis]), np.prod(idx_xsection_shape))) scattered = np.copy(data) scattered[tuple(idx)] = updates[tuple(updates_idx)] return scattered class Scatter(Base): @staticmethod def export_scatter_without_axis(): # type: () -> None node = onnx.helper.make_node( 'Scatter', inputs=['data', 'indices', 'updates'], outputs=['y'], ) data = np.zeros((3, 3), dtype=np.float32) indices = np.array([[1, 0, 2], [0, 2, 1]], dtype=np.int64) updates = np.array([[1.0, 1.1, 1.2], [2.0, 2.1, 2.2]], dtype=np.float32) y = scatter(data, indices, updates) # print(y) produces # [[2.0, 1.1, 0.0], # [1.0, 0.0, 2.2], # [0.0, 2.1, 1.2]] expect(node, inputs=[data, indices, updates], outputs=[y], name='test_scatter_without_axis', opset_imports=[helper.make_opsetid("", 10)]) @staticmethod def export_scatter_with_axis(): # type: () -> None axis = 1 node = onnx.helper.make_node( 'Scatter', inputs=['data', 'indices', 'updates'], outputs=['y'], axis=axis, ) data = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32) indices = np.array([[1, 3]], dtype=np.int64) updates = np.array([[1.1, 2.1]], dtype=np.float32) y = scatter(data, indices, updates, axis=axis) # print(y) produces # [[1.0, 1.1, 3.0, 2.1, 5.0]] expect(node, inputs=[data, indices, updates], outputs=[y], name='test_scatter_with_axis', opset_imports=[helper.make_opsetid("", 10)])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect def apply_adam(r, t, x, g, v, h, norm_coefficient, norm_coefficient_post, alpha, beta, epsilon): # type: ignore # Add gradient of regularization term. g_regularized = norm_coefficient * x + g # Update momentum. v_new = alpha * v + (1 - alpha) * g_regularized # Update second-order momentum. h_new = beta * h + (1 - beta) * (g_regularized * g_regularized) # Compute element-wise square root. h_sqrt = np.sqrt(h_new) + epsilon # Adjust learning rate. r_adjusted = None if t > 0: # Consider bias correction on momentums. r_adjusted = r * np.sqrt(1 - beta**t) / (1 - alpha**t) else: # No bias correction on momentums. r_adjusted = r # Apply Adam update rule. x_new = x - r_adjusted * (v_new / h_sqrt) # It's possible to apply regularization in the end. x_final = (1 - norm_coefficient_post) * x_new return x_final, v_new, h_new class Adam(Base): @staticmethod def export_adam(): # type: () -> None # Define operator attributes. norm_coefficient = 0.001 alpha = 0.95 beta = 0.1 epsilon = 1e-7 # Create operator. node = onnx.helper.make_node('Adam', inputs=['R', 'T', 'X', 'G', 'V', 'H'], outputs=['X_new', 'V_new', 'H_new'], norm_coefficient=norm_coefficient, alpha=alpha, beta=beta, epsilon=epsilon, domain='ai.onnx.training' ) # Define operator inputs. r = np.array(0.1, dtype=np.float32) # scalar t = np.array(0, dtype=np.int64) # scalar x = np.array([1.2, 2.8], dtype=np.float32) g = np.array([-0.94, -2.5], dtype=np.float32) v = np.array([1.7, 3.6], dtype=np.float32) h = np.array([0.1, 0.1], dtype=np.float32) # Compute expected outputs of Adam. x_new, v_new, h_new = apply_adam(r, t, x, g, v, h, norm_coefficient, 0.0, alpha, beta, epsilon) # Check results. expect(node, inputs=[r, t, x, g, v, h], outputs=[x_new, v_new, h_new], name='test_adam', opset_imports=[onnx.helper.make_opsetid('ai.onnx.training', 1)]) @staticmethod def export_adam_multiple(): # type: () -> None # Define operator attributes. norm_coefficient = 0.001 alpha = 0.95 beta = 0.85 epsilon = 1e-2 node = onnx.helper.make_node('Adam', inputs=['R', 'T', 'X1', 'X2', 'G1', 'G2', 'V1', 'V2', 'H1', 'H2'], outputs=['X1_new', 'X2_new', 'V1_new', 'V2_new', 'H1_new', 'H2_new'], norm_coefficient=norm_coefficient, alpha=alpha, beta=beta, domain='ai.onnx.training' ) # Define operator inputs. r = np.array(0.1, dtype=np.float32) # scalar t = np.array(0, dtype=np.int64) # scalar x1 = np.array([1.0], dtype=np.float32) g1 = np.array([-1.0], dtype=np.float32) v1 = np.array([2.0], dtype=np.float32) h1 = np.array([0.5], dtype=np.float32) x2 = np.array([1.0, 2.0], dtype=np.float32) g2 = np.array([-1.0, -3.0], dtype=np.float32) v2 = np.array([4.0, 1.0], dtype=np.float32) h2 = np.array([1.0, 10.0], dtype=np.float32) # Compute expected outputs of Adam. x1_new, v1_new, h1_new = apply_adam(r, t, x1, g1, v1, h1, norm_coefficient, 0.0, alpha, beta, epsilon) x2_new, v2_new, h2_new = apply_adam(r, t, x2, g2, v2, h2, norm_coefficient, 0.0, alpha, beta, epsilon) # Check results. expect(node, inputs=[r, t, x1, x2, g1, g2, v1, v2, h1, h2], outputs=[x1_new, x2_new, v1_new, v2_new, h1_new, h2_new], name='test_adam_multiple', opset_imports=[onnx.helper.make_opsetid('ai.onnx.training', 1)])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Compress(Base): @staticmethod def export_compress_0(): # type: () -> None node = onnx.helper.make_node( 'Compress', inputs=['input', 'condition'], outputs=['output'], axis=0, ) input = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32) condition = np.array([0, 1, 1]) output = np.compress(condition, input, axis=0) #print(output) #[[ 3. 4.] # [ 5. 6.]] expect(node, inputs=[input, condition.astype(np.bool)], outputs=[output], name='test_compress_0') @staticmethod def export_compress_1(): # type: () -> None node = onnx.helper.make_node( 'Compress', inputs=['input', 'condition'], outputs=['output'], axis=1, ) input = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32) condition = np.array([0, 1]) output = np.compress(condition, input, axis=1) #print(output) #[[ 2.] # [ 4.] # [ 6.]] expect(node, inputs=[input, condition.astype(np.bool)], outputs=[output], name='test_compress_1') @staticmethod def export_compress_default_axis(): # type: () -> None node = onnx.helper.make_node( 'Compress', inputs=['input', 'condition'], outputs=['output'], ) input = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32) condition = np.array([0, 1, 0, 0, 1]) output = np.compress(condition, input) #print(output) #[ 2., 5.] expect(node, inputs=[input, condition.astype(np.bool)], outputs=[output], name='test_compress_default_axis') @staticmethod def export_compress_negative_axis(): # type: () -> None node = onnx.helper.make_node( 'Compress', inputs=['input', 'condition'], outputs=['output'], axis=-1, ) input = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32) condition = np.array([0, 1]) output = np.compress(condition, input, axis=-1) # print(output) #[[ 2.] # [ 4.] # [ 6.]] expect(node, inputs=[input, condition.astype(np.bool)], outputs=[output], name='test_compress_negative_axis')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Relu(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Relu', inputs=['x'], outputs=['y'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.clip(x, 0, np.inf) expect(node, inputs=[x], outputs=[y], name='test_relu')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Sub(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Sub', inputs=['x', 'y'], outputs=['z'], ) x = np.array([1, 2, 3]).astype(np.float32) y = np.array([3, 2, 1]).astype(np.float32) z = x - y # expected output [-2., 0., 2.] expect(node, inputs=[x, y], outputs=[z], name='test_sub_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.random.randn(3, 4, 5).astype(np.float32) z = x - y expect(node, inputs=[x, y], outputs=[z], name='test_sub') @staticmethod def export_sub_broadcast(): # type: () -> None node = onnx.helper.make_node( 'Sub', inputs=['x', 'y'], outputs=['z'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.random.randn(5).astype(np.float32) z = x - y expect(node, inputs=[x, y], outputs=[z], name='test_sub_bcast')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore from typing import Any, Sequence import onnx from onnx import NodeProto from ..base import Base from . import expect class TfIdfVectorizerHelper(): def __init__(self, **params): # type: (*Any) -> None # Attr names mode = str('mode') min_gram_length = str('min_gram_length') max_gram_length = str('max_gram_length') max_skip_count = str('max_skip_count') ngram_counts = str('ngram_counts') ngram_indexes = str('ngram_indexes') pool_int64s = str('pool_int64s') required_attr = [mode, min_gram_length, max_gram_length, max_skip_count, ngram_counts, ngram_indexes, pool_int64s] for i in required_attr: assert i in params, "Missing attribute: {0}".format(i) self.mode = params[mode] self.min_gram_length = params[min_gram_length] self.max_gram_length = params[max_gram_length] self.max_skip_count = params[max_skip_count] self.ngram_counts = params[ngram_counts] self.ngram_indexes = params[ngram_indexes] self.pool_int64s = params[pool_int64s] def make_node_noweights(self): # type: () -> NodeProto return onnx.helper.make_node( 'TfIdfVectorizer', inputs=['X'], outputs=['Y'], mode=self.mode, min_gram_length=self.min_gram_length, max_gram_length=self.max_gram_length, max_skip_count=self.max_skip_count, ngram_counts=self.ngram_counts, ngram_indexes=self.ngram_indexes, pool_int64s=self.pool_int64s ) class TfIdfVectorizer(Base): @staticmethod def export_tf_only_bigrams_skip0(): # type: () -> None input = np.array([1, 1, 3, 3, 3, 7, 8, 6, 7, 5, 6, 8]).astype(np.int32) output = np.array([0., 0., 0., 0., 1., 1., 1.]).astype(np.float32) ngram_counts = np.array([0, 4]).astype(np.int64) ngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64) pool_int64s = np.array([2, 3, 5, 4, # unigrams 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams helper = TfIdfVectorizerHelper( mode='TF', min_gram_length=2, max_gram_length=2, max_skip_count=0, ngram_counts=ngram_counts, ngram_indexes=ngram_indexes, pool_int64s=pool_int64s ) node = helper.make_node_noweights() expect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_only_bigrams_skip0') @staticmethod def export_tf_batch_onlybigrams_skip0(): # type: () -> None input = np.array([[1, 1, 3, 3, 3, 7], [8, 6, 7, 5, 6, 8]]).astype(np.int32) output = np.array([[0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 1., 0., 1.]]).astype(np.float32) ngram_counts = np.array([0, 4]).astype(np.int64) ngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64) pool_int64s = np.array([2, 3, 5, 4, # unigrams 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams helper = TfIdfVectorizerHelper( mode='TF', min_gram_length=2, max_gram_length=2, max_skip_count=0, ngram_counts=ngram_counts, ngram_indexes=ngram_indexes, pool_int64s=pool_int64s ) node = helper.make_node_noweights() expect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_batch_onlybigrams_skip0') @staticmethod def export_tf_onlybigrams_levelempty(): # type: () -> None input = np.array([1, 1, 3, 3, 3, 7, 8, 6, 7, 5, 6, 8]).astype(np.int32) output = np.array([1., 1., 1.]).astype(np.float32) ngram_counts = np.array([0, 0]).astype(np.int64) ngram_indexes = np.array([0, 1, 2]).astype(np.int64) pool_int64s = np.array([ # unigrams none 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams helper = TfIdfVectorizerHelper( mode='TF', min_gram_length=2, max_gram_length=2, max_skip_count=0, ngram_counts=ngram_counts, ngram_indexes=ngram_indexes, pool_int64s=pool_int64s ) node = helper.make_node_noweights() expect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_onlybigrams_levelempty') @staticmethod def export_tf_onlybigrams_skip5(): # type: () -> None input = np.array([1, 1, 3, 3, 3, 7, 8, 6, 7, 5, 6, 8]).astype(np.int32) output = np.array([0., 0., 0., 0., 1., 3., 1.]).astype(np.float32) ngram_counts = np.array([0, 4]).astype(np.int64) ngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64) pool_int64s = np.array([2, 3, 5, 4, # unigrams 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams helper = TfIdfVectorizerHelper( mode='TF', min_gram_length=2, max_gram_length=2, max_skip_count=5, ngram_counts=ngram_counts, ngram_indexes=ngram_indexes, pool_int64s=pool_int64s ) node = helper.make_node_noweights() expect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_onlybigrams_skip5') @staticmethod def export_tf_batch_onlybigrams_skip5(): # type: () -> None input = np.array([[1, 1, 3, 3, 3, 7], [8, 6, 7, 5, 6, 8]]).astype(np.int32) output = np.array([[0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 1., 1., 1.]]).astype(np.float32) ngram_counts = np.array([0, 4]).astype(np.int64) ngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64) pool_int64s = np.array([2, 3, 5, 4, # unigrams 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams helper = TfIdfVectorizerHelper( mode='TF', min_gram_length=2, max_gram_length=2, max_skip_count=5, ngram_counts=ngram_counts, ngram_indexes=ngram_indexes, pool_int64s=pool_int64s ) node = helper.make_node_noweights() expect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_batch_onlybigrams_skip5') @staticmethod def export_tf_uniandbigrams_skip5(): # type: () -> None input = np.array([1, 1, 3, 3, 3, 7, 8, 6, 7, 5, 6, 8]).astype(np.int32) output = np.array([0., 3., 1., 0., 1., 3., 1.]).astype(np.float32) ngram_counts = np.array([0, 4]).astype(np.int64) ngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64) pool_int64s = np.array([2, 3, 5, 4, # unigrams 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams helper = TfIdfVectorizerHelper( mode='TF', min_gram_length=1, max_gram_length=2, max_skip_count=5, ngram_counts=ngram_counts, ngram_indexes=ngram_indexes, pool_int64s=pool_int64s ) node = helper.make_node_noweights() expect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_uniandbigrams_skip5') @staticmethod def export_tf_batch_uniandbigrams_skip5(): # type: () -> None input = np.array([[1, 1, 3, 3, 3, 7], [8, 6, 7, 5, 6, 8]]).astype(np.int32) output = np.array([[0., 3., 0., 0., 0., 0., 0.], [0., 0., 1., 0., 1., 1., 1.]]).astype(np.float32) ngram_counts = np.array([0, 4]).astype(np.int64) ngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64) pool_int64s = np.array([2, 3, 5, 4, # unigrams 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams helper = TfIdfVectorizerHelper( mode='TF', min_gram_length=1, max_gram_length=2, max_skip_count=5, ngram_counts=ngram_counts, ngram_indexes=ngram_indexes, pool_int64s=pool_int64s ) node = helper.make_node_noweights() expect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_batch_uniandbigrams_skip5')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect def scatter_nd_impl(data, indices, updates): # type: (np.ndarray, np.ndarray, np.ndarray) -> np.ndarray # Check tensor shapes assert indices.shape[-1] <= len(data.shape) assert updates.shape == indices.shape[:-1] + data.shape[indices.shape[-1]:] # Compute output output = np.copy(data) for i in np.ndindex(indices.shape[:-1]): # NOTE: The order of iteration in this loop is not specified. # In particular, indices should not have duplicate entries: that is, if idx1 != idx2, then indices[idx1] != indices[idx2]. # This ensures that the output value does not depend on the iteration order. output[indices[i]] = updates[i] return output class ScatterND(Base): @staticmethod def export_scatternd(): # type: () -> None node = onnx.helper.make_node( 'ScatterND', inputs=['data', 'indices', 'updates'], outputs=['y'], ) data = np.array( [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]], [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.float32) indices = np.array([[0], [2]], dtype=np.int64) updates = np.array( [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]], dtype=np.float32) # Expecting output as np.array( # [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], # [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]], # [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]], # [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.float32) output = scatter_nd_impl(data, indices, updates) expect(node, inputs=[data, indices, updates], outputs=[output], name='test_scatternd')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect # The below ScatterElements' numpy implementation is from https://stackoverflow.com/a/46204790/11767360 def scatter_elements(data, indices, updates, axis=0): # type: ignore if axis < 0: axis = data.ndim + axis idx_xsection_shape = indices.shape[:axis] + indices.shape[axis + 1:] def make_slice(arr, axis, i): # type: ignore slc = [slice(None)] * arr.ndim slc[axis] = i return slc def unpack(packed): # type: ignore unpacked = packed[0] for i in range(1, len(packed)): unpacked = unpacked, packed[i] return unpacked # We use indices and axis parameters to create idx # idx is in a form that can be used as a NumPy advanced indices for scattering of updates param. in data idx = [[unpack(np.indices(idx_xsection_shape).reshape(indices.ndim - 1, -1)), indices[tuple(make_slice(indices, axis, i))].reshape(1, -1)[0]] for i in range(indices.shape[axis])] idx = list(np.concatenate(idx, axis=1)) idx.insert(axis, idx.pop()) # updates_idx is a NumPy advanced indices for indexing of elements in the updates updates_idx = list(idx) updates_idx.pop(axis) updates_idx.insert(axis, np.repeat(np.arange(indices.shape[axis]), np.prod(idx_xsection_shape))) scattered = np.copy(data) scattered[tuple(idx)] = updates[tuple(updates_idx)] return scattered class ScatterElements(Base): @staticmethod def export_scatter_elements_without_axis(): # type: () -> None node = onnx.helper.make_node( 'ScatterElements', inputs=['data', 'indices', 'updates'], outputs=['y'], ) data = np.zeros((3, 3), dtype=np.float32) indices = np.array([[1, 0, 2], [0, 2, 1]], dtype=np.int64) updates = np.array([[1.0, 1.1, 1.2], [2.0, 2.1, 2.2]], dtype=np.float32) y = scatter_elements(data, indices, updates) # print(y) produces # [[2.0, 1.1, 0.0], # [1.0, 0.0, 2.2], # [0.0, 2.1, 1.2]] expect(node, inputs=[data, indices, updates], outputs=[y], name='test_scatter_elements_without_axis') @staticmethod def export_scatter_elements_with_axis(): # type: () -> None axis = 1 node = onnx.helper.make_node( 'ScatterElements', inputs=['data', 'indices', 'updates'], outputs=['y'], axis=axis, ) data = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32) indices = np.array([[1, 3]], dtype=np.int64) updates = np.array([[1.1, 2.1]], dtype=np.float32) y = scatter_elements(data, indices, updates, axis) # print(y) produces # [[1.0, 1.1, 3.0, 2.1, 5.0]] expect(node, inputs=[data, indices, updates], outputs=[y], name='test_scatter_elements_with_axis') @staticmethod def export_scatter_elements_with_negative_indices(): # type: () -> None axis = 1 node = onnx.helper.make_node( 'ScatterElements', inputs=['data', 'indices', 'updates'], outputs=['y'], axis=axis, ) data = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32) indices = np.array([[1, -3]], dtype=np.int64) updates = np.array([[1.1, 2.1]], dtype=np.float32) y = scatter_elements(data, indices, updates, axis) # print(y) produces # [[1.0, 1.1, 2.1, 4.0, 5.0]] expect(node, inputs=[data, indices, updates], outputs=[y], name='test_scatter_elements_with_negative_indices')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Xor(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Xor', inputs=['x', 'y'], outputs=['xor'], ) # 2d x = (np.random.randn(3, 4) > 0).astype(np.bool) y = (np.random.randn(3, 4) > 0).astype(np.bool) z = np.logical_xor(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_xor2d') # 3d x = (np.random.randn(3, 4, 5) > 0).astype(np.bool) y = (np.random.randn(3, 4, 5) > 0).astype(np.bool) z = np.logical_xor(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_xor3d') # 4d x = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool) y = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool) z = np.logical_xor(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_xor4d') @staticmethod def export_xor_broadcast(): # type: () -> None node = onnx.helper.make_node( 'Xor', inputs=['x', 'y'], outputs=['xor'], ) # 3d vs 1d x = (np.random.randn(3, 4, 5) > 0).astype(np.bool) y = (np.random.randn(5) > 0).astype(np.bool) z = np.logical_xor(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_xor_bcast3v1d') # 3d vs 2d x = (np.random.randn(3, 4, 5) > 0).astype(np.bool) y = (np.random.randn(4, 5) > 0).astype(np.bool) z = np.logical_xor(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_xor_bcast3v2d') # 4d vs 2d x = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool) y = (np.random.randn(5, 6) > 0).astype(np.bool) z = np.logical_xor(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_xor_bcast4v2d') # 4d vs 3d x = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool) y = (np.random.randn(4, 5, 6) > 0).astype(np.bool) z = np.logical_xor(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_xor_bcast4v3d') # 4d vs 4d x = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool) y = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool) z = np.logical_xor(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_xor_bcast4v4d')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Unsqueeze(Base): @staticmethod def export_unsqueeze_one_axis(): # type: () -> None x = np.random.randn(3, 4, 5).astype(np.float32) for i in range(x.ndim): node = onnx.helper.make_node( 'Unsqueeze', inputs=['x'], outputs=['y'], axes=[i], ) y = np.expand_dims(x, axis=i) expect(node, inputs=[x], outputs=[y], name='test_unsqueeze_axis_' + str(i)) @staticmethod def export_unsqueeze_two_axes(): # type: () -> None x = np.random.randn(3, 4, 5).astype(np.float32) node = onnx.helper.make_node( 'Unsqueeze', inputs=['x'], outputs=['y'], axes=[1, 4], ) y = np.expand_dims(x, axis=1) y = np.expand_dims(y, axis=4) expect(node, inputs=[x], outputs=[y], name='test_unsqueeze_two_axes') @staticmethod def export_unsqueeze_three_axes(): # type: () -> None x = np.random.randn(3, 4, 5).astype(np.float32) node = onnx.helper.make_node( 'Unsqueeze', inputs=['x'], outputs=['y'], axes=[2, 4, 5], ) y = np.expand_dims(x, axis=2) y = np.expand_dims(y, axis=4) y = np.expand_dims(y, axis=5) expect(node, inputs=[x], outputs=[y], name='test_unsqueeze_three_axes') @staticmethod def export_unsqueeze_unsorted_axes(): # type: () -> None x = np.random.randn(3, 4, 5).astype(np.float32) node = onnx.helper.make_node( 'Unsqueeze', inputs=['x'], outputs=['y'], axes=[5, 4, 2], ) y = np.expand_dims(x, axis=2) y = np.expand_dims(y, axis=4) y = np.expand_dims(y, axis=5) expect(node, inputs=[x], outputs=[y], name='test_unsqueeze_unsorted_axes') @staticmethod def export_unsqueeze_negative_axes(): # type: () -> None node = onnx.helper.make_node( 'Unsqueeze', inputs=['x'], outputs=['y'], axes=[-2], ) x = np.random.randn(1, 3, 1, 5).astype(np.float32) y = np.expand_dims(x, axis=-2) expect(node, inputs=[x], outputs=[y], name='test_unsqueeze_negative_axes')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class ReverseSequence(Base): @staticmethod def export_reversesequence_time(): # type: () -> None node = onnx.helper.make_node( 'ReverseSequence', inputs=['x', 'sequence_lens'], outputs=['y'], time_axis=0, batch_axis=1, ) x = np.array([[0.0, 4.0, 8.0, 12.0], [1.0, 5.0, 9.0, 13.0], [2.0, 6.0, 10.0, 14.0], [3.0, 7.0, 11.0, 15.0]], dtype=np.float32) sequence_lens = np.array([4, 3, 2, 1], dtype=np.int64) y = np.array([[3.0, 6.0, 9.0, 12.0], [2.0, 5.0, 8.0, 13.0], [1.0, 4.0, 10.0, 14.0], [0.0, 7.0, 11.0, 15.0]], dtype=np.float32) expect(node, inputs=[x, sequence_lens], outputs=[y], name='test_reversesequence_time') @staticmethod def export_reversesequence_batch(): # type: () -> None node = onnx.helper.make_node( 'ReverseSequence', inputs=['x', 'sequence_lens'], outputs=['y'], time_axis=1, batch_axis=0, ) x = np.array([[0.0, 1.0, 2.0, 3.0], [4.0, 5.0, 6.0, 7.0], [8.0, 9.0, 10.0, 11.0], [12.0, 13.0, 14.0, 15.0]], dtype=np.float32) sequence_lens = np.array([1, 2, 3, 4], dtype=np.int64) y = np.array([[0.0, 1.0, 2.0, 3.0], [5.0, 4.0, 6.0, 7.0], [10.0, 9.0, 8.0, 11.0], [15.0, 14.0, 13.0, 12.0]], dtype=np.float32) expect(node, inputs=[x, sequence_lens], outputs=[y], name='test_reversesequence_batch')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Scan(Base): @staticmethod def export_scan_8(): # type: () -> None # Given an input sequence [x1, ..., xN], sum up its elements using a scan # returning the final state (x1+x2+...+xN) as well the scan_output # [x1, x1+x2, ..., x1+x2+...+xN] # # create graph to represent scan body sum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2]) next = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2]) sum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2]) scan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2]) add_node = onnx.helper.make_node( 'Add', inputs=['sum_in', 'next'], outputs=['sum_out'] ) id_node = onnx.helper.make_node( 'Identity', inputs=['sum_out'], outputs=['scan_out'] ) scan_body = onnx.helper.make_graph( [add_node, id_node], 'scan_body', [sum_in, next], [sum_out, scan_out] ) # create scan op node no_sequence_lens = '' # optional input, not supplied node = onnx.helper.make_node( 'Scan', inputs=[no_sequence_lens, 'initial', 'x'], outputs=['y', 'z'], num_scan_inputs=1, body=scan_body ) # create inputs for batch-size 1, sequence-length 3, inner dimension 2 initial = np.array([0, 0]).astype(np.float32).reshape((1, 2)) x = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((1, 3, 2)) # final state computed = [1 + 3 + 5, 2 + 4 + 6] y = np.array([9, 12]).astype(np.float32).reshape((1, 2)) # scan-output computed z = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((1, 3, 2)) expect(node, inputs=[initial, x], outputs=[y, z], name='test_scan_sum', opset_imports=[onnx.helper.make_opsetid("", 8)]) @staticmethod def export_scan_9(): # type: () -> None # Given an input sequence [x1, ..., xN], sum up its elements using a scan # returning the final state (x1+x2+...+xN) as well the scan_output # [x1, x1+x2, ..., x1+x2+...+xN] # # create graph to represent scan body sum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2]) next = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2]) sum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2]) scan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2]) add_node = onnx.helper.make_node( 'Add', inputs=['sum_in', 'next'], outputs=['sum_out'] ) id_node = onnx.helper.make_node( 'Identity', inputs=['sum_out'], outputs=['scan_out'] ) scan_body = onnx.helper.make_graph( [add_node, id_node], 'scan_body', [sum_in, next], [sum_out, scan_out] ) # create scan op node node = onnx.helper.make_node( 'Scan', inputs=['initial', 'x'], outputs=['y', 'z'], num_scan_inputs=1, body=scan_body ) # create inputs for sequence-length 3, inner dimension 2 initial = np.array([0, 0]).astype(np.float32).reshape((2,)) x = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((3, 2)) # final state computed = [1 + 3 + 5, 2 + 4 + 6] y = np.array([9, 12]).astype(np.float32).reshape((2,)) # scan-output computed z = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((3, 2)) expect(node, inputs=[initial, x], outputs=[y, z], name='test_scan9_sum', opset_imports=[onnx.helper.make_opsetid("", 9)])
import numpy as np # type: ignore import itertools from typing import Text, Sequence def get_pad_shape(auto_pad, # type: Text input_spatial_shape, # type: Sequence[int] kernel_spatial_shape, # type: Sequence[int] strides_spatial, # type: Sequence[int] output_spatial_shape # type: Sequence[int] ): # type: (...) -> Sequence[int] pad_shape = [0] * len(input_spatial_shape) if auto_pad in ('SAME_UPPER', 'SAME_LOWER'): for i in range(len(input_spatial_shape)): pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial[i] + \ kernel_spatial_shape[i] - input_spatial_shape[i] elif auto_pad == 'VALID': pass return pad_shape def get_output_shape(auto_pad, # type: Text input_spatial_shape, # type: Sequence[int] kernel_spatial_shape, # type: Sequence[int] strides_spatial # type: Sequence[int] ): # type: (...) -> Sequence[int] out_shape = [0] * len(input_spatial_shape) if auto_pad in ('SAME_UPPER', 'SAME_LOWER'): for i in range(len(input_spatial_shape)): out_shape[i] = int( np.ceil( float( input_spatial_shape[i]) / float( strides_spatial[i]))) elif auto_pad == 'VALID': for i in range(len(input_spatial_shape)): out_shape[i] = int(np.ceil(float(input_spatial_shape[i] - (kernel_spatial_shape[i] - 1)) / float(strides_spatial[i]))) return out_shape def pool(padded, # type: np.ndarray x_shape, # type: Sequence[int] kernel_shape, # type: Sequence[int] strides_shape, # type: Sequence[int] out_shape, # type: Sequence[int] pad_shape, # type: Sequence[int] pooling_type, # type: Text count_include_pad=0 # type: int ): # type: (...) -> np.ndarray spatial_size = len(x_shape) - 2 y = np.zeros([x_shape[0], x_shape[1]] + list(out_shape)) for shape in itertools.product(range(x_shape[0]), range(x_shape[1]), *[range(int( (x_shape[i + 2] + pad_shape[i] - kernel_shape[i]) / strides_shape[i] + 1)) for i in range(spatial_size)]): window = padded[shape[0], shape[1]] window_vals = np.array([window[i] for i in list( itertools.product( *[range(strides_shape[i] * shape[i + 2], strides_shape[i] * shape[i + 2] + kernel_shape[i]) for i in range(spatial_size)]) )]) if pooling_type == 'AVG': f = np.average elif pooling_type == 'MAX': f = np.max else: raise NotImplementedError( 'Pooling type {} does not support. Should be AVG, MAX'.format(pooling_type)) if count_include_pad == 1 and pooling_type == 'AVG': y[shape] = f(window_vals) else: y[shape] = f(window_vals[np.where(~np.isnan(window_vals))]) return y.astype(np.float32)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class HardSigmoid(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'HardSigmoid', inputs=['x'], outputs=['y'], alpha=0.5, beta=0.6 ) x = np.array([-1, 0, 1]).astype(np.float32) y = np.clip(x * 0.5 + 0.6, 0, 1) # expected output [0.1, 0.6, 1.] expect(node, inputs=[x], outputs=[y], name='test_hardsigmoid_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.clip(x * 0.5 + 0.6, 0, 1) expect(node, inputs=[x], outputs=[y], name='test_hardsigmoid') @staticmethod def export_hardsigmoid_default(): # type: () -> None default_alpha = 0.2 default_beta = 0.5 node = onnx.helper.make_node( 'HardSigmoid', inputs=['x'], outputs=['y'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.clip(x * default_alpha + default_beta, 0, 1) expect(node, inputs=[x], outputs=[y], name='test_hardsigmoid_default')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class ReduceL2(Base): @staticmethod def export_do_not_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [2] keepdims = 0 node = onnx.helper.make_node( 'ReduceL2', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims ) data = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape) #print(data) #[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]] reduced = np.sqrt(np.sum( a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1)) #print(reduced) #[[2.23606798, 5.], # [7.81024968, 10.63014581], # [13.45362405, 16.2788206]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_do_not_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.sqrt(np.sum( a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1)) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_do_not_keepdims_random') @staticmethod def export_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [2] keepdims = 1 node = onnx.helper.make_node( 'ReduceL2', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims ) data = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape) #print(data) #[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]] reduced = np.sqrt(np.sum( a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1)) #print(reduced) #[[[2.23606798], [5.]] # [[7.81024968], [10.63014581]] # [[13.45362405], [16.2788206 ]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_keep_dims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.sqrt(np.sum( a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1)) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_keep_dims_random') @staticmethod def export_default_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = None keepdims = 1 node = onnx.helper.make_node( 'ReduceL2', inputs=['data'], outputs=['reduced'], keepdims=keepdims ) data = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape) #print(data) #[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]] reduced = np.sqrt(np.sum( a=np.square(data), axis=axes, keepdims=keepdims == 1)) #print(reduced) #[[[25.49509757]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_default_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.sqrt(np.sum( a=np.square(data), axis=axes, keepdims=keepdims == 1)) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_default_axes_keepdims_random') @staticmethod def export_negative_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [-1] keepdims = 1 node = onnx.helper.make_node( 'ReduceL2', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims ) data = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape) # print(data) #[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]] reduced = np.sqrt(np.sum( a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1)) # print(reduced) #[[[2.23606798], [5.]] # [[7.81024968], [10.63014581]] # [[13.45362405], [16.2788206 ]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_negative_axes_keep_dims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.sqrt(np.sum( a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1)) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_negative_axes_keep_dims_random')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Shape(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Shape', inputs=['x'], outputs=['y'], ) x = np.array([ [1, 2, 3], [4, 5, 6], ]).astype(np.float32) y = np.array([ 2, 3, ]).astype(np.int64) expect(node, inputs=[x], outputs=[y], name='test_shape_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.array(x.shape).astype(np.int64) expect(node, inputs=[x], outputs=[y], name='test_shape')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class MatMulInteger(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node('MatMulInteger', inputs=['A', 'B', 'a_zero_point', 'b_zero_point'], outputs=['Y'],) A = np.array([[11, 7, 3], [10, 6, 2], [9, 5, 1], [8, 4, 0], ], dtype=np.uint8) a_zero_point = np.array([12], dtype=np.uint8) B = np.array([[1, 4], [2, 5], [3, 6], ], dtype=np.uint8) b_zero_point = np.array([0], dtype=np.uint8) output = np.array([[-38, -83], [-44, -98], [-50, -113], [-56, -128], ], dtype=np.int32) expect(node, inputs=[A, B, a_zero_point, b_zero_point], outputs=[output], name='test_matmulinteger')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class ReduceProd(Base): @staticmethod def export_do_not_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 0 node = onnx.helper.make_node( 'ReduceProd', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32) reduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[3., 8.] # [35., 48.] # [99., 120.]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_random') @staticmethod def export_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 1 node = onnx.helper.make_node( 'ReduceProd', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32) reduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[[3., 8.]] # [[35., 48.]] # [[99., 120.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_random') @staticmethod def export_default_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = None keepdims = 1 node = onnx.helper.make_node( 'ReduceProd', inputs=['data'], outputs=['reduced'], keepdims=keepdims) data = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32) reduced = np.prod(data, axis=axes, keepdims=keepdims == 1) #print(reduced) #[[[4.790016e+08]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.prod(data, axis=axes, keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_random') @staticmethod def export_negative_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [-2] keepdims = 1 node = onnx.helper.make_node( 'ReduceProd', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32) reduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1) # print(reduced) #[[[3., 8.]] # [[35., 48.]] # [[99., 120.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_random')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import random import onnx from ..base import Base from . import expect from onnx import helper def dropout(X, drop_probability=0.5, seed=0, training_mode=False, return_mask=False): # type: ignore if drop_probability == 0 or training_mode is False: if return_mask is True: return X, np.ones(X.shape, dtype=bool) else: return X np.random.seed(seed) mask = np.random.uniform(0, 1.0, X.shape) >= drop_probability scale = (1 / (1 - drop_probability)) if return_mask is True: return mask * X * scale, mask.astype(bool) else: return mask * X * scale class Dropout(Base): # Inferencing tests. @staticmethod def export_default(): # type: () -> None seed = np.int64(0) node = onnx.helper.make_node( 'Dropout', inputs=['x'], outputs=['y'], seed=seed ) x = np.random.randn(3, 4, 5).astype(np.float32) y = dropout(x) expect(node, inputs=[x], outputs=[y], name='test_dropout_default') @staticmethod def export_default_ratio(): # type: () -> None seed = np.int64(0) node = onnx.helper.make_node( 'Dropout', inputs=['x', 'r'], outputs=['y'], seed=seed ) r = np.float32(0.1) x = np.random.randn(3, 4, 5).astype(np.float32) y = dropout(x, r) expect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio') @staticmethod def export_default_mask(): # type: () -> None seed = np.int64(0) node = onnx.helper.make_node( 'Dropout', inputs=['x'], outputs=['y', 'z'], seed=seed ) x = np.random.randn(3, 4, 5).astype(np.float32) y, z = dropout(x, return_mask=True) expect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask') @staticmethod def export_default_mask_ratio(): # type: () -> None seed = np.int64(0) node = onnx.helper.make_node( 'Dropout', inputs=['x', 'r'], outputs=['y', 'z'], seed=seed ) r = np.float32(0.1) x = np.random.randn(3, 4, 5).astype(np.float32) y, z = dropout(x, r, return_mask=True) expect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio') # Training tests. @staticmethod def export_training_default(): # type: () -> None seed = np.int64(0) node = onnx.helper.make_node( 'Dropout', inputs=['x', 'r', 't'], outputs=['y'], seed=seed ) x = np.random.randn(3, 4, 5).astype(np.float32) r = np.float32(0.5) t = np.bool_(True) y = dropout(x, r, training_mode=t) expect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default') @staticmethod def export_training_default_ratio_mask(): # type: () -> None seed = np.int64(0) node = onnx.helper.make_node( 'Dropout', inputs=['x', 'r', 't'], outputs=['y', 'z'], seed=seed ) x = np.random.randn(3, 4, 5).astype(np.float32) r = np.float32(0.5) t = np.bool_(True) y, z = dropout(x, r, training_mode=t, return_mask=True) expect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask') @staticmethod def export_training(): # type: () -> None seed = np.int64(0) node = onnx.helper.make_node( 'Dropout', inputs=['x', 'r', 't'], outputs=['y'], seed=seed ) x = np.random.randn(3, 4, 5).astype(np.float32) r = np.float32(0.75) t = np.bool_(True) y = dropout(x, r, training_mode=t) expect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout') @staticmethod def export_training_ratio_mask(): # type: () -> None seed = np.int64(0) node = onnx.helper.make_node( 'Dropout', inputs=['x', 'r', 't'], outputs=['y', 'z'], seed=seed ) x = np.random.randn(3, 4, 5).astype(np.float32) r = np.float32(0.75) t = np.bool_(True) y, z = dropout(x, r, training_mode=t, return_mask=True) expect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask') @staticmethod def export_training_default_zero_ratio(): # type: () -> None seed = np.int64(0) node = onnx.helper.make_node( 'Dropout', inputs=['x', 'r', 't'], outputs=['y'], seed=seed ) x = np.random.randn(3, 4, 5).astype(np.float32) r = np.float32(0.0) t = np.bool_(True) y = dropout(x, r, training_mode=t) expect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio') @staticmethod def export_training_default_zero_ratio_mask(): # type: () -> None seed = np.int64(0) node = onnx.helper.make_node( 'Dropout', inputs=['x', 'r', 't'], outputs=['y', 'z'], seed=seed ) x = np.random.randn(3, 4, 5).astype(np.float32) r = np.float32(0.0) t = np.bool_(True) y, z = dropout(x, r, training_mode=t, return_mask=True) expect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask') # Old dropout tests @staticmethod def export_default_old(): # type: () -> None node = onnx.helper.make_node( 'Dropout', inputs=['x'], outputs=['y'], ) x = np.array([-1, 0, 1]).astype(np.float32) y = x expect(node, inputs=[x], outputs=[y], name='test_dropout_default_old', opset_imports=[helper.make_opsetid("", 11)]) @staticmethod def export_random_old(): # type: () -> None node = onnx.helper.make_node( 'Dropout', inputs=['x'], outputs=['y'], ratio=.2, ) x = np.random.randn(3, 4, 5).astype(np.float32) y = x expect(node, inputs=[x], outputs=[y], name='test_dropout_random_old', opset_imports=[helper.make_opsetid("", 11)])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Constant(Base): @staticmethod def export(): # type: () -> None values = np.random.randn(5, 5).astype(np.float32) node = onnx.helper.make_node( 'Constant', inputs=[], outputs=['values'], value=onnx.helper.make_tensor( name='const_tensor', data_type=onnx.TensorProto.FLOAT, dims=values.shape, vals=values.flatten().astype(float), ), ) expect(node, inputs=[], outputs=[values], name='test_constant')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Sum(Base): @staticmethod def export(): # type: () -> None data_0 = np.array([3, 0, 2]).astype(np.float32) data_1 = np.array([1, 3, 4]).astype(np.float32) data_2 = np.array([2, 6, 6]).astype(np.float32) result = np.array([6, 9, 12]).astype(np.float32) node = onnx.helper.make_node( 'Sum', inputs=['data_0', 'data_1', 'data_2'], outputs=['result'], ) expect(node, inputs=[data_0, data_1, data_2], outputs=[result], name='test_sum_example') node = onnx.helper.make_node( 'Sum', inputs=['data_0'], outputs=['result'], ) expect(node, inputs=[data_0], outputs=[data_0], name='test_sum_one_input') result = np.add(data_0, data_1) node = onnx.helper.make_node( 'Sum', inputs=['data_0', 'data_1'], outputs=['result'], ) expect(node, inputs=[data_0, data_1], outputs=[result], name='test_sum_two_inputs')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class ReduceMax(Base): @staticmethod def export_do_not_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 0 node = onnx.helper.make_node( 'ReduceMax', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[20., 2.] # [40., 2.] # [60., 2.]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_random') @staticmethod def export_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 1 node = onnx.helper.make_node( 'ReduceMax', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[[20., 2.]] # [[40., 2.]] # [[60., 2.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_random') @staticmethod def export_default_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = None keepdims = 1 node = onnx.helper.make_node( 'ReduceMax', inputs=['data'], outputs=['reduced'], keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1) #print(reduced) [[[60.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdim_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdims_random') @staticmethod def export_negative_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [-2] keepdims = 1 node = onnx.helper.make_node( 'ReduceMax', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1) # print(reduced) #[[[20., 2.]] # [[40., 2.]] # [[60., 2.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_random')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Conv(Base): @staticmethod def export(): # type: () -> None x = np.array([[[[0., 1., 2., 3., 4.], # (1, 1, 5, 5) input tensor [5., 6., 7., 8., 9.], [10., 11., 12., 13., 14.], [15., 16., 17., 18., 19.], [20., 21., 22., 23., 24.]]]]).astype(np.float32) W = np.array([[[[1., 1., 1.], # (1, 1, 3, 3) tensor for convolution weights [1., 1., 1.], [1., 1., 1.]]]]).astype(np.float32) # Convolution with padding node_with_padding = onnx.helper.make_node( 'Conv', inputs=['x', 'W'], outputs=['y'], kernel_shape=[3, 3], # Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1 pads=[1, 1, 1, 1], ) y_with_padding = np.array([[[[12., 21., 27., 33., 24.], # (1, 1, 5, 5) output tensor [33., 54., 63., 72., 51.], [63., 99., 108., 117., 81.], [93., 144., 153., 162., 111.], [72., 111., 117., 123., 84.]]]]).astype(np.float32) expect(node_with_padding, inputs=[x, W], outputs=[y_with_padding], name='test_basic_conv_with_padding') # Convolution without padding node_without_padding = onnx.helper.make_node( 'Conv', inputs=['x', 'W'], outputs=['y'], kernel_shape=[3, 3], # Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1 pads=[0, 0, 0, 0], ) y_without_padding = np.array([[[[54., 63., 72.], # (1, 1, 3, 3) output tensor [99., 108., 117.], [144., 153., 162.]]]]).astype(np.float32) expect(node_without_padding, inputs=[x, W], outputs=[y_without_padding], name='test_basic_conv_without_padding') @staticmethod def export_conv_with_strides(): # type: () -> None x = np.array([[[[0., 1., 2., 3., 4.], # (1, 1, 7, 5) input tensor [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.]]]]).astype(np.float32) W = np.array([[[[1., 1., 1.], # (1, 1, 3, 3) tensor for convolution weights [1., 1., 1.], [1., 1., 1.]]]]).astype(np.float32) # Convolution with strides=2 and padding node_with_padding = onnx.helper.make_node( 'Conv', inputs=['x', 'W'], outputs=['y'], kernel_shape=[3, 3], pads=[1, 1, 1, 1], strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1 ) y_with_padding = np.array([[[[12., 27., 24.], # (1, 1, 4, 3) output tensor [63., 108., 81.], [123., 198., 141.], [112., 177., 124.]]]]).astype(np.float32) expect(node_with_padding, inputs=[x, W], outputs=[y_with_padding], name='test_conv_with_strides_padding') # Convolution with strides=2 and no padding node_without_padding = onnx.helper.make_node( 'Conv', inputs=['x', 'W'], outputs=['y'], kernel_shape=[3, 3], pads=[0, 0, 0, 0], strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1 ) y_without_padding = np.array([[[[54., 72.], # (1, 1, 3, 2) output tensor [144., 162.], [234., 252.]]]]).astype(np.float32) expect(node_without_padding, inputs=[x, W], outputs=[y_without_padding], name='test_conv_with_strides_no_padding') # Convolution with strides=2 and padding only along one dimension (the H dimension in NxCxHxW tensor) node_with_asymmetric_padding = onnx.helper.make_node( 'Conv', inputs=['x', 'W'], outputs=['y'], kernel_shape=[3, 3], pads=[1, 0, 1, 0], strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1 ) y_with_asymmetric_padding = np.array([[[[21., 33.], # (1, 1, 4, 2) output tensor [99., 117.], [189., 207.], [171., 183.]]]]).astype(np.float32) expect(node_with_asymmetric_padding, inputs=[x, W], outputs=[y_with_asymmetric_padding], name='test_conv_with_strides_and_asymmetric_padding')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Greater(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Greater', inputs=['x', 'y'], outputs=['greater'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.random.randn(3, 4, 5).astype(np.float32) z = np.greater(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_greater') @staticmethod def export_greater_broadcast(): # type: () -> None node = onnx.helper.make_node( 'Greater', inputs=['x', 'y'], outputs=['greater'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.random.randn(5).astype(np.float32) z = np.greater(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_greater_bcast')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Less(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Less', inputs=['x', 'y'], outputs=['less'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.random.randn(3, 4, 5).astype(np.float32) z = np.less(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_less') @staticmethod def export_less_broadcast(): # type: () -> None node = onnx.helper.make_node( 'Less', inputs=['x', 'y'], outputs=['less'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.random.randn(5).astype(np.float32) z = np.less(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_less_bcast')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class CumSum(Base): @staticmethod def export_cumsum_1d(): # type: () -> None node = onnx.helper.make_node( 'CumSum', inputs=['x', 'axis'], outputs=['y'] ) x = np.array([1., 2., 3., 4., 5.]).astype(np.float64) axis = np.array([0]).astype(np.int32) y = np.array([1., 3., 6., 10., 15.]).astype(np.float64) expect(node, inputs=[x, axis], outputs=[y], name='test_cumsum_1d') @staticmethod def export_cumsum_1d_exclusive(): # type: () -> None node = onnx.helper.make_node( 'CumSum', inputs=['x', 'axis'], outputs=['y'], exclusive=1 ) x = np.array([1., 2., 3., 4., 5.]).astype(np.float64) axis = np.array([0]).astype(np.int32) y = np.array([0., 1., 3., 6., 10.]).astype(np.float64) expect(node, inputs=[x, axis], outputs=[y], name='test_cumsum_1d_exclusive') @staticmethod def export_cumsum_1d_reverse(): # type: () -> None node = onnx.helper.make_node( 'CumSum', inputs=['x', 'axis'], outputs=['y'], reverse=1 ) x = np.array([1., 2., 3., 4., 5.]).astype(np.float64) axis = np.array([0]).astype(np.int32) y = np.array([15., 14., 12., 9., 5.]).astype(np.float64) expect(node, inputs=[x, axis], outputs=[y], name='test_cumsum_1d_reverse') @staticmethod def export_cumsum_1d_reverse_exclusive(): # type: () -> None node = onnx.helper.make_node( 'CumSum', inputs=['x', 'axis'], outputs=['y'], reverse=1 ) x = np.array([1., 2., 3., 4., 5.]).astype(np.float64) axis = np.array([0]).astype(np.int32) y = np.array([14., 12., 9., 5., 0.]).astype(np.float64) expect(node, inputs=[x, axis], outputs=[y], name='test_cumsum_1d_reverse_exclusive') @staticmethod def export_cumsum_2d_axis_0(): # type: () -> None node = onnx.helper.make_node( 'CumSum', inputs=['x', 'axis'], outputs=['y'], ) x = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float64).reshape((2, 3)) axis = np.array([0]).astype(np.int32) y = np.array([1., 2., 3., 5., 7., 9.]).astype(np.float64).reshape((2, 3)) expect(node, inputs=[x, axis], outputs=[y], name='test_cumsum_2d_axis_0') @staticmethod def export_cumsum_2d_axis_1(): # type: () -> None node = onnx.helper.make_node( 'CumSum', inputs=['x', 'axis'], outputs=['y'], ) x = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float64).reshape((2, 3)) axis = np.array([1]).astype(np.int32) y = np.array([1., 3., 6., 4., 9., 15.]).astype(np.float64).reshape((2, 3)) expect(node, inputs=[x, axis], outputs=[y], name='test_cumsum_2d_axis_1') @staticmethod def export_cumsum_2d_negative_axis(): # type: () -> None node = onnx.helper.make_node( 'CumSum', inputs=['x', 'axis'], outputs=['y'], ) x = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float64).reshape((2, 3)) axis = np.array([-1]).astype(np.int32) y = np.array([1., 3., 6., 4., 9., 15.]).astype(np.float64).reshape((2, 3)) expect(node, inputs=[x, axis], outputs=[y], name='test_cumsum_2d_negative_axis')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class ReduceSumSquare(Base): @staticmethod def export_do_not_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 0 node = onnx.helper.make_node( 'ReduceSumSquare', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32) reduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[10., 20.] # [74., 100.] # [202., 244.]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_random') @staticmethod def export_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 1 node = onnx.helper.make_node( 'ReduceSumSquare', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32) reduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[[10., 20.]] # [[74., 100.]] # [[202., 244.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_random') @staticmethod def export_default_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = None keepdims = 1 node = onnx.helper.make_node( 'ReduceSumSquare', inputs=['data'], outputs=['reduced'], keepdims=keepdims) data = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32) reduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1) #print(reduced) #[[[650.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_random') @staticmethod def export_negative_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [-2] keepdims = 1 node = onnx.helper.make_node( 'ReduceSumSquare', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32) reduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1) # print(reduced) #[[[10., 20.s]] # [[74., 100.]] # [[202., 244.]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_random')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore from typing import Any, Tuple import onnx from ..base import Base from . import expect class LSTM_Helper(): def __init__(self, **params): # type: (*Any) -> None # LSTM Input Names X = str('X') W = str('W') R = str('R') B = str('B') H_0 = str('initial_h') C_0 = str('initial_c') P = str('P') number_of_gates = 4 number_of_peepholes = 3 required_inputs = [X, W, R] for i in required_inputs: assert i in params, "Missing Required Input: {0}".format(i) self.num_directions = params[W].shape[0] if self.num_directions == 1: for k in params.keys(): if k != X: params[k] = np.squeeze(params[k], axis=0) hidden_size = params[R].shape[-1] batch_size = params[X].shape[1] b = params[B] if B in params else np.zeros(2 * number_of_gates * hidden_size, dtype=np.float32) p = params[P] if P in params else np.zeros(number_of_peepholes * hidden_size, dtype=np.float32) h_0 = params[H_0] if H_0 in params else np.zeros((batch_size, hidden_size), dtype=np.float32) c_0 = params[C_0] if C_0 in params else np.zeros((batch_size, hidden_size), dtype=np.float32) self.X = params[X] self.W = params[W] self.R = params[R] self.B = b self.P = p self.H_0 = h_0 self.C_0 = c_0 else: raise NotImplementedError() def f(self, x): # type: (np.ndarray) -> np.ndarray return 1 / (1 + np.exp(-x)) def g(self, x): # type: (np.ndarray) -> np.ndarray return np.tanh(x) def h(self, x): # type: (np.ndarray) -> np.ndarray return np.tanh(x) def step(self): # type: () -> Tuple[np.ndarray, np.ndarray] [p_i, p_o, p_f] = np.split(self.P, 3) h_list = [] H_t = self.H_0 C_t = self.C_0 for x in np.split(self.X, self.X.shape[0], axis=0): gates = np.dot(x, np.transpose(self.W)) + np.dot(H_t, np.transpose(self.R)) + np.add( *np.split(self.B, 2)) i, o, f, c = np.split(gates, 4, -1) i = self.f(i + p_i * C_t) f = self.f(f + p_f * C_t) c = self.g(c) C = f * C_t + i * c o = self.f(o + p_o * C) H = o * self.h(C) h_list.append(H) H_t = H C_t = C concatenated = np.concatenate(h_list) if self.num_directions == 1: output = np.expand_dims(concatenated, 1) return output, h_list[-1] class LSTM(Base): @staticmethod def export_defaults(): # type: () -> None input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32) input_size = 2 hidden_size = 3 weight_scale = 0.1 number_of_gates = 4 node = onnx.helper.make_node( 'LSTM', inputs=['X', 'W', 'R'], outputs=['', 'Y'], hidden_size=hidden_size ) W = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32) R = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32) lstm = LSTM_Helper(X=input, W=W, R=R) _, Y_h = lstm.step() expect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_lstm_defaults') @staticmethod def export_initial_bias(): # type: () -> None input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32) input_size = 3 hidden_size = 4 weight_scale = 0.1 custom_bias = 0.1 number_of_gates = 4 node = onnx.helper.make_node( 'LSTM', inputs=['X', 'W', 'R', 'B'], outputs=['', 'Y'], hidden_size=hidden_size ) W = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32) R = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32) # Adding custom bias W_B = custom_bias * np.ones((1, number_of_gates * hidden_size)).astype(np.float32) R_B = np.zeros((1, number_of_gates * hidden_size)).astype(np.float32) B = np.concatenate((W_B, R_B), 1) lstm = LSTM_Helper(X=input, W=W, R=R, B=B) _, Y_h = lstm.step() expect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_lstm_with_initial_bias') @staticmethod def export_peepholes(): # type: () -> None input = np.array([[[1., 2., 3., 4.], [5., 6., 7., 8.]]]).astype(np.float32) input_size = 4 hidden_size = 3 weight_scale = 0.1 number_of_gates = 4 number_of_peepholes = 3 node = onnx.helper.make_node( 'LSTM', inputs=['X', 'W', 'R', 'B', 'sequence_lens', 'initial_h', 'initial_c', 'P'], outputs=['', 'Y'], hidden_size=hidden_size ) # Initializing Inputs W = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32) R = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32) B = np.zeros((1, 2 * number_of_gates * hidden_size)).astype(np.float32) seq_lens = np.repeat(input.shape[0], input.shape[1]).astype(np.int32) init_h = np.zeros((1, input.shape[1], hidden_size)).astype(np.float32) init_c = np.zeros((1, input.shape[1], hidden_size)).astype(np.float32) P = weight_scale * np.ones((1, number_of_peepholes * hidden_size)).astype(np.float32) lstm = LSTM_Helper(X=input, W=W, R=R, B=B, P=P, initial_c=init_c, initial_h=init_h) _, Y_h = lstm.step() expect(node, inputs=[input, W, R, B, seq_lens, init_h, init_c, P], outputs=[Y_h.astype(np.float32)], name='test_lstm_with_peepholes')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Cosh(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Cosh', inputs=['x'], outputs=['y'], ) x = np.array([-1, 0, 1]).astype(np.float32) y = np.cosh(x) # expected output [1.54308069, 1., 1.54308069] expect(node, inputs=[x], outputs=[y], name='test_cosh_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.cosh(x) expect(node, inputs=[x], outputs=[y], name='test_cosh')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Clip(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Clip', inputs=['x', 'min', 'max'], outputs=['y'], ) x = np.array([-2, 0, 2]).astype(np.float32) min_val = np.float32(-1) max_val = np.float32(1) y = np.clip(x, min_val, max_val) # expected output [-1., 0., 1.] expect(node, inputs=[x, min_val, max_val], outputs=[y], name='test_clip_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.clip(x, min_val, max_val) expect(node, inputs=[x, min_val, max_val], outputs=[y], name='test_clip') node = onnx.helper.make_node( 'Clip', inputs=['x', 'min', 'max'], outputs=['y'], ) min_val = np.float32(-5) max_val = np.float32(5) x = np.array([-1, 0, 1]).astype(np.float32) y = np.array([-1, 0, 1]).astype(np.float32) expect(node, inputs=[x, min_val, max_val], outputs=[y], name='test_clip_inbounds') x = np.array([-6, 0, 6]).astype(np.float32) y = np.array([-5, 0, 5]).astype(np.float32) expect(node, inputs=[x, min_val, max_val], outputs=[y], name='test_clip_outbounds') x = np.array([-1, 0, 6]).astype(np.float32) y = np.array([-1, 0, 5]).astype(np.float32) expect(node, inputs=[x, min_val, max_val], outputs=[y], name='test_clip_splitbounds') @staticmethod def export_clip_default(): # type: () -> None node = onnx.helper.make_node( 'Clip', inputs=['x', 'min'], outputs=['y'], ) min_val = np.float32(0) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.clip(x, min_val, np.inf) expect(node, inputs=[x, min_val], outputs=[y], name='test_clip_default_min') no_min = "" # optional input, not supplied node = onnx.helper.make_node( 'Clip', inputs=['x', no_min, 'max'], outputs=['y'], ) max_val = np.float32(0) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.clip(x, -np.inf, max_val) expect(node, inputs=[x, max_val], outputs=[y], name='test_clip_default_max') no_max = "" # optional input, not supplied node = onnx.helper.make_node( 'Clip', inputs=['x', no_min, no_max], outputs=['y'], ) x = np.array([-1, 0, 1]).astype(np.float32) y = np.array([-1, 0, 1]).astype(np.float32) expect(node, inputs=[x], outputs=[y], name='test_clip_default_inbounds') @staticmethod def export_clip_default_int8(): # type: () -> None node = onnx.helper.make_node( 'Clip', inputs=['x', 'min'], outputs=['y'], ) min_val = np.int8(0) x = np.random.randn(3, 4, 5).astype(np.int8) y = np.clip(x, min_val, np.iinfo(np.int8).max) expect(node, inputs=[x, min_val], outputs=[y], name='test_clip_default_int8_min') no_min = "" # optional input, not supplied node = onnx.helper.make_node( 'Clip', inputs=['x', no_min, 'max'], outputs=['y'], ) max_val = np.int8(0) x = np.random.randn(3, 4, 5).astype(np.int8) y = np.clip(x, np.iinfo(np.int8).min, max_val) expect(node, inputs=[x, max_val], outputs=[y], name='test_clip_default_int8_max') no_max = "" # optional input, not supplied node = onnx.helper.make_node( 'Clip', inputs=['x', no_min, no_max], outputs=['y'], ) x = np.array([-1, 0, 1]).astype(np.int8) y = np.array([-1, 0, 1]).astype(np.int8) expect(node, inputs=[x], outputs=[y], name='test_clip_default_int8_inbounds')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Elu(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Elu', inputs=['x'], outputs=['y'], alpha=2.0 ) x = np.array([-1, 0, 1]).astype(np.float32) # expected output [-1.2642411, 0., 1.] y = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0 expect(node, inputs=[x], outputs=[y], name='test_elu_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0 expect(node, inputs=[x], outputs=[y], name='test_elu') @staticmethod def export_elu_default(): # type: () -> None default_alpha = 1.0 node = onnx.helper.make_node( 'Elu', inputs=['x'], outputs=['y'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * default_alpha expect(node, inputs=[x], outputs=[y], name='test_elu_default')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore from typing import Any, Tuple import onnx from ..base import Base from . import expect class GRU_Helper(): def __init__(self, **params): # type: (*Any) -> None # GRU Input Names X = str('X') W = str('W') R = str('R') B = str('B') H_0 = str('initial_h') LBR = str('linear_before_reset') number_of_gates = 3 required_inputs = [X, W, R] for i in required_inputs: assert i in params, "Missing Required Input: {0}".format(i) self.num_directions = params[W].shape[0] if self.num_directions == 1: for k in params.keys(): if k != X: params[k] = np.squeeze(params[k], axis=0) hidden_size = params[R].shape[-1] batch_size = params[X].shape[1] b = params[B] if B in params else np.zeros(2 * number_of_gates * hidden_size) h_0 = params[H_0] if H_0 in params else np.zeros((batch_size, hidden_size)) lbr = params[LBR] if LBR in params else 0 self.X = params[X] self.W = params[W] self.R = params[R] self.B = b self.H_0 = h_0 self.LBR = lbr else: raise NotImplementedError() def f(self, x): # type: (np.ndarray) -> np.ndarray return 1 / (1 + np.exp(-x)) def g(self, x): # type: (np.ndarray) -> np.ndarray return np.tanh(x) def step(self): # type: () -> Tuple[np.ndarray, np.ndarray] h_list = [] [w_z, w_r, w_h] = np.split(self.W, 3) [r_z, r_r, r_h] = np.split(self.R, 3) [w_bz, w_br, w_bh, r_bz, r_br, r_bh] = np.split(self.B, 6) gates_w = np.transpose(np.concatenate((w_z, w_r))) gates_r = np.transpose(np.concatenate((r_z, r_r))) gates_b = np.add(np.concatenate((w_bz, w_br)), np.concatenate((r_bz, r_br))) H_t = self.H_0 for x in np.split(self.X, self.X.shape[0], axis=0): gates = np.dot(x, gates_w) + np.dot(H_t, gates_r) + gates_b z, r = np.split(gates, 2, -1) z = self.f(z) r = self.f(r) h_default = self.g(np.dot(x, np.transpose(w_h)) + np.dot(r * H_t, np.transpose(r_h)) + w_bh + r_bh) h_linear = self.g(np.dot(x, np.transpose(w_h)) + r * (np.dot(H_t, np.transpose(r_h)) + r_bh) + w_bh) h = h_linear if self.LBR else h_default H = (1 - z) * h + z * H_t h_list.append(H) H_t = H concatenated = np.concatenate(h_list) if self.num_directions == 1: output = np.expand_dims(concatenated, 1) return output, h_list[-1] class GRU(Base): @staticmethod def export_defaults(): # type: () -> None input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32) input_size = 2 hidden_size = 5 weight_scale = 0.1 number_of_gates = 3 node = onnx.helper.make_node( 'GRU', inputs=['X', 'W', 'R'], outputs=['', 'Y'], hidden_size=hidden_size ) W = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32) R = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32) gru = GRU_Helper(X=input, W=W, R=R) _, Y_h = gru.step() expect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_gru_defaults') @staticmethod def export_initial_bias(): # type: () -> None input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32) input_size = 3 hidden_size = 3 weight_scale = 0.1 custom_bias = 0.1 number_of_gates = 3 node = onnx.helper.make_node( 'GRU', inputs=['X', 'W', 'R', 'B'], outputs=['', 'Y'], hidden_size=hidden_size ) W = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32) R = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32) # Adding custom bias W_B = custom_bias * np.ones((1, number_of_gates * hidden_size)).astype(np.float32) R_B = np.zeros((1, number_of_gates * hidden_size)).astype(np.float32) B = np.concatenate((W_B, R_B), axis=1) gru = GRU_Helper(X=input, W=W, R=R, B=B) _, Y_h = gru.step() expect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_with_initial_bias') @staticmethod def export_seq_length(): # type: () -> None input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]], [[10., 11., 12.], [13., 14., 15.], [16., 17., 18.]]]).astype(np.float32) input_size = 3 hidden_size = 5 number_of_gates = 3 node = onnx.helper.make_node( 'GRU', inputs=['X', 'W', 'R', 'B'], outputs=['', 'Y'], hidden_size=hidden_size ) W = np.random.randn(1, number_of_gates * hidden_size, input_size).astype(np.float32) R = np.random.randn(1, number_of_gates * hidden_size, hidden_size).astype(np.float32) # Adding custom bias W_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32) R_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32) B = np.concatenate((W_B, R_B), axis=1) gru = GRU_Helper(X=input, W=W, R=R, B=B) _, Y_h = gru.step() expect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_seq_length')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Sign(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Sign', inputs=['x'], outputs=['y'], ) x = np.array(range(-5, 6)).astype(np.float32) y = np.sign(x) expect(node, inputs=[x], outputs=[y], name='test_sign')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Sinh(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Sinh', inputs=['x'], outputs=['y'], ) x = np.array([-1, 0, 1]).astype(np.float32) y = np.sinh(x) # expected output [-1.17520118, 0., 1.17520118] expect(node, inputs=[x], outputs=[y], name='test_sinh_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.sinh(x) expect(node, inputs=[x], outputs=[y], name='test_sinh')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Softplus(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Softplus', inputs=['x'], outputs=['y'], ) x = np.array([-1, 0, 1]).astype(np.float32) y = np.log(np.exp(x) + 1) # expected output [0.31326166, 0.69314718, 1.31326163] expect(node, inputs=[x], outputs=[y], name='test_softplus_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.log(np.exp(x) + 1) expect(node, inputs=[x], outputs=[y], name='test_softplus')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect def topk_sorted_implementation(X, k, axis, largest): # type: ignore sorted_indices = np.argsort(X, axis=axis) sorted_values = np.sort(X, axis=axis) if largest: sorted_indices = np.flip(sorted_indices, axis=axis) sorted_values = np.flip(sorted_values, axis=axis) topk_sorted_indices = np.take(sorted_indices, np.arange(k), axis=axis) topk_sorted_values = np.take(sorted_values, np.arange(k), axis=axis) return topk_sorted_values, topk_sorted_indices class TopK(Base): @staticmethod def export_top_k(): # type: () -> None axis = 1 largest = 1 k = 3 node = onnx.helper.make_node( 'TopK', inputs=['x', 'k'], outputs=['values', 'indices'], axis=axis ) X = np.array([ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], ], dtype=np.float32) K = np.array([k], dtype=np.int64) values_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest) #print(values_ref) #[[ 3. 2. 1.] # [ 7. 6. 5.] # [11. 10. 9.]] #print(indices_ref) #[[3 2 1] # [3 2 1] # [3 2 1]] expect(node, inputs=[X, K], outputs=[values_ref, indices_ref], name='test_top_k') @staticmethod def export_top_k_smallest(): # type: () -> None axis = 1 largest = 0 sorted = 1 k = 3 node = onnx.helper.make_node( 'TopK', inputs=['x', 'k'], outputs=['values', 'indices'], axis=axis, largest=largest, sorted=sorted ) X = np.array([ [0, 1, 2, 3], [4, 5, 6, 7], [11, 10, 9, 8], ], dtype=np.float32) K = np.array([k], dtype=np.int64) values_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest) #print(values_ref) #[[ 0. 1. 2.] # [ 4. 5. 6.] # [ 8. 9. 10.]] #print(indices_ref) #[[0 1 2] # [0 1 2] # [3 2 1]] expect(node, inputs=[X, K], outputs=[values_ref, indices_ref], name='test_top_k_smallest') @staticmethod def export_top_k_negative_axis(): # type: () -> None axis = -1 largest = 1 k = 3 node = onnx.helper.make_node( 'TopK', inputs=['x', 'k'], outputs=['values', 'indices'], axis=axis ) X = np.array([ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], ], dtype=np.float32) K = np.array([k], dtype=np.int64) values_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest) # print(values_ref) #[[ 3. 2. 1.] # [ 7. 6. 5.] # [11. 10. 9.]] # print(indices_ref) #[[3 2 1] # [3 2 1] # [3 2 1]] expect(node, inputs=[X, K], outputs=[values_ref, indices_ref], name='test_top_k_negative_axis')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Sigmoid(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Sigmoid', inputs=['x'], outputs=['y'], ) x = np.array([-1, 0, 1]).astype(np.float32) y = 1.0 / (1.0 + np.exp(np.negative(x))) # expected output [0.26894143, 0.5, 0.7310586] expect(node, inputs=[x], outputs=[y], name='test_sigmoid_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = 1.0 / (1.0 + np.exp(np.negative(x))) expect(node, inputs=[x], outputs=[y], name='test_sigmoid')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from onnx.backend.test.case.base import Base from onnx.backend.test.case.node import expect class Squeeze(Base): @staticmethod def export_squeeze(): # type: () -> None node = onnx.helper.make_node( 'Squeeze', inputs=['x'], outputs=['y'], axes=[0], ) x = np.random.randn(1, 3, 4, 5).astype(np.float32) y = np.squeeze(x, axis=0) expect(node, inputs=[x], outputs=[y], name='test_squeeze') @staticmethod def export_squeeze_negative_axes(): # type: () -> None node = onnx.helper.make_node( 'Squeeze', inputs=['x'], outputs=['y'], axes=[-2], ) x = np.random.randn(1, 3, 1, 5).astype(np.float32) y = np.squeeze(x, axis=-2) expect(node, inputs=[x], outputs=[y], name='test_squeeze_negative_axes')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Mod(Base): @staticmethod def export_mod_mixed_sign_float64(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], fmod=1 ) x = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float64) y = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float64) z = np.fmod(x, y) # expected output [-0.1, 0.4, 5. , 0.1, -0.4, 3.] expect(node, inputs=[x, y], outputs=[z], name='test_mod_mixed_sign_float64') @staticmethod def export_mod_mixed_sign_float32(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], fmod=1 ) x = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float32) y = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float32) z = np.fmod(x, y) # expected output [-0.10000038, 0.39999962, 5. , 0.10000038, -0.39999962, 3.] expect(node, inputs=[x, y], outputs=[z], name='test_mod_mixed_sign_float32') @staticmethod def export_mod_mixed_sign_float16(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], fmod=1 ) x = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float16) y = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float16) z = np.fmod(x, y) # expected output [-0.10156, 0.3984 , 5. , 0.10156, -0.3984 , 3.] expect(node, inputs=[x, y], outputs=[z], name='test_mod_mixed_sign_float16') @staticmethod def export_mod_mixed_sign_int64(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], ) x = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int64) y = np.array([2, -3, 8, -2, 3, 5]).astype(np.int64) z = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3] expect(node, inputs=[x, y], outputs=[z], name='test_mod_mixed_sign_int64') @staticmethod def export_mod_mixed_sign_int32(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], ) x = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int32) y = np.array([2, -3, 8, -2, 3, 5]).astype(np.int32) z = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3] expect(node, inputs=[x, y], outputs=[z], name='test_mod_mixed_sign_int32') @staticmethod def export_mod_mixed_sign_int16(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], ) x = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int16) y = np.array([2, -3, 8, -2, 3, 5]).astype(np.int16) z = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3] expect(node, inputs=[x, y], outputs=[z], name='test_mod_mixed_sign_int16') @staticmethod def export_mod_mixed_sign_int8(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], ) x = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int8) y = np.array([2, -3, 8, -2, 3, 5]).astype(np.int8) z = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3] expect(node, inputs=[x, y], outputs=[z], name='test_mod_mixed_sign_int8') @staticmethod def export_mod_uint8(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], ) x = np.array([4, 7, 5]).astype(np.uint8) y = np.array([2, 3, 8]).astype(np.uint8) z = np.mod(x, y) # expected output [0, 1, 5] expect(node, inputs=[x, y], outputs=[z], name='test_mod_uint8') @staticmethod def export_mod_uint16(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], ) x = np.array([4, 7, 5]).astype(np.uint16) y = np.array([2, 3, 8]).astype(np.uint16) z = np.mod(x, y) # expected output [0, 1, 5] expect(node, inputs=[x, y], outputs=[z], name='test_mod_uint16') @staticmethod def export_mod_uint32(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], ) x = np.array([4, 7, 5]).astype(np.uint32) y = np.array([2, 3, 8]).astype(np.uint32) z = np.mod(x, y) # expected output [0, 1, 5] expect(node, inputs=[x, y], outputs=[z], name='test_mod_uint32') @staticmethod def export_mod_uint64(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], ) x = np.array([4, 7, 5]).astype(np.uint64) y = np.array([2, 3, 8]).astype(np.uint64) z = np.mod(x, y) # expected output [0, 1, 5] expect(node, inputs=[x, y], outputs=[z], name='test_mod_uint64') @staticmethod def export_mod_int64_fmod(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], fmod=1 ) x = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int64) y = np.array([2, -3, 8, -2, 3, 5]).astype(np.int64) z = np.fmod(x, y) # expected output [ 0, 1, 5, 0, -1, 3] expect(node, inputs=[x, y], outputs=[z], name='test_mod_int64_fmod') @staticmethod def export_mod_broadcast(): # type: () -> None node = onnx.helper.make_node( 'Mod', inputs=['x', 'y'], outputs=['z'], ) x = np.arange(0, 30).reshape([3, 2, 5]) y = np.array([7]) z = np.mod(x, y) z # array([[[0, 1, 2, 3, 4], # [5, 6, 0, 1, 2]], # [[3, 4, 5, 6, 0], # [1, 2, 3, 4, 5]], # [[6, 0, 1, 2, 3], # [4, 5, 6, 0, 1]]], dtype=int32) expect(node, inputs=[x, y], outputs=[z], name='test_mod_broadcast')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Greater(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'GreaterOrEqual', inputs=['x', 'y'], outputs=['greater_equal'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.random.randn(3, 4, 5).astype(np.float32) z = np.greater_equal(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_greater_equal') @staticmethod def export_greater_broadcast(): # type: () -> None node = onnx.helper.make_node( 'GreaterOrEqual', inputs=['x', 'y'], outputs=['greater_equal'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.random.randn(5).astype(np.float32) z = np.greater_equal(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_greater_equal_bcast')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Identity(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Identity', inputs=['x'], outputs=['y'], ) data = np.array([[[ [1, 2], [3, 4], ]]], dtype=np.float32) expect(node, inputs=[data], outputs=[data], name='test_identity')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect def apply_momentum(t, r, x, g, v, norm_coefficient, alpha, beta): # type: ignore # Add gradient of regularization term. g_regularized = norm_coefficient * x + g # Coefficient of gradient should be 1 at the first iteration. beta_adjusted = beta if t > 0 else 1 # Update momentum. v_new = alpha * v + beta_adjusted * g_regularized # Apply SG with momentum update rule. x_new = x - r * v_new return x_new, v_new def apply_nesterov(t, r, x, g, v, norm_coefficient, alpha, beta): # type: ignore # Add gradient of regularization term. g_regularized = norm_coefficient * x + g # Coefficient of gradient should be 1 at the first iteration. beta_adjusted = beta if t > 0 else 1 # Update momentum. v_new = alpha * v + beta_adjusted * g_regularized # Apply Nesterov with momentum update rule. x_new = x - r * (g_regularized + alpha * v_new) return x_new, v_new class Momentum(Base): @staticmethod def export_momentum(): # type: () -> None # Define operator attributes. norm_coefficient = 0.001 alpha = 0.95 beta = 0.1 # Create operator. node = onnx.helper.make_node('Momentum', inputs=['R', 'T', 'X', 'G', 'V'], outputs=['X_new', 'V_new'], norm_coefficient=norm_coefficient, alpha=alpha, beta=beta, mode='standard', domain='ai.onnx.training' ) # Define operator inputs. r = np.array(0.1, dtype=np.float32) # scalar t = np.array(0, dtype=np.int64) # scalar x = np.array([1.2, 2.8], dtype=np.float32) g = np.array([-0.94, -2.5], dtype=np.float32) v = np.array([1.7, 3.6], dtype=np.float32) # Compute expected outputs of Momentum. x_new, v_new = apply_momentum(r, t, x, g, v, norm_coefficient, alpha, beta) # Check results. expect(node, inputs=[r, t, x, g, v], outputs=[x_new, v_new], name='test_momentum', opset_imports=[onnx.helper.make_opsetid('ai.onnx.training', 1)]) @staticmethod def export_nesterov_momentum(): # type: () -> None # Define operator attributes. norm_coefficient = 0.01 alpha = 0.95 beta = 1.0 # Create operator. node = onnx.helper.make_node('Momentum', inputs=['R', 'T', 'X', 'G', 'V'], outputs=['X_new', 'V_new'], norm_coefficient=norm_coefficient, alpha=alpha, beta=beta, mode='nesterov', domain='ai.onnx.training' ) # Define operator inputs. r = np.array(0.1, dtype=np.float32) # scalar t = np.array(0, dtype=np.int64) # scalar x = np.array([1.2, 2.8], dtype=np.float32) g = np.array([-0.94, -2.5], dtype=np.float32) v = np.array([1.7, 3.6], dtype=np.float32) # Compute expected outputs of Adagrad. x_new, v_new = apply_nesterov(r, t, x, g, v, norm_coefficient, alpha, beta) # Check results. expect(node, inputs=[r, t, x, g, v], outputs=[x_new, v_new], name='test_nesterov_momentum', opset_imports=[onnx.helper.make_opsetid('ai.onnx.training', 1)]) @staticmethod def export_momentum_multiple(): # type: () -> None # Define operator attributes. norm_coefficient = 0.001 alpha = 0.95 beta = 0.85 node = onnx.helper.make_node('Momentum', inputs=['R', 'T', 'X1', 'X2', 'G1', 'G2', 'H1', 'H2'], outputs=['X1_new', 'X2_new', 'V1_new', 'V2_new'], norm_coefficient=norm_coefficient, alpha=alpha, beta=beta, mode='standard', domain='ai.onnx.training' ) # Define operator inputs. r = np.array(0.1, dtype=np.float32) # scalar t = np.array(0, dtype=np.int64) # scalar x1 = np.array([1.0], dtype=np.float32) g1 = np.array([-1.0], dtype=np.float32) v1 = np.array([2.0], dtype=np.float32) x2 = np.array([1.0, 2.0], dtype=np.float32) g2 = np.array([-1.0, -3.0], dtype=np.float32) v2 = np.array([4.0, 1.0], dtype=np.float32) # Compute expected outputs of Momentum. x1_new, v1_new = apply_momentum(r, t, x1, g1, v1, norm_coefficient, alpha, beta) x2_new, v2_new = apply_momentum(r, t, x2, g2, v2, norm_coefficient, alpha, beta) # Check results. expect(node, inputs=[r, t, x1, x2, g1, g2, v1, v2], outputs=[x1_new, x2_new, v1_new, v2_new], name='test_momentum_multiple', opset_imports=[onnx.helper.make_opsetid('ai.onnx.training', 1)])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Exp(Base): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Exp', inputs=['x'], outputs=['y'], ) x = np.array([-1, 0, 1]).astype(np.float32) y = np.exp(x) # expected output [0.36787945, 1., 2.71828175] expect(node, inputs=[x], outputs=[y], name='test_exp_example') x = np.random.randn(3, 4, 5).astype(np.float32) y = np.exp(x) expect(node, inputs=[x], outputs=[y], name='test_exp')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class ConstantOfShape(Base): @staticmethod def export_float_ones(): # type: () -> None x = np.array([4, 3, 2]).astype(np.int64) tensor_value = onnx.helper.make_tensor("value", onnx.TensorProto.FLOAT, [1], [1]) node = onnx.helper.make_node( 'ConstantOfShape', inputs=['x'], outputs=['y'], value=tensor_value, ) y = np.ones(x, dtype=np.float32) expect(node, inputs=[x], outputs=[y], name='test_constantofshape_float_ones') @staticmethod def export_int32_zeros(): # type: () -> None x = np.array([10, 6]).astype(np.int64) tensor_value = onnx.helper.make_tensor("value", onnx.TensorProto.INT32, [1], [0]) node = onnx.helper.make_node( 'ConstantOfShape', inputs=['x'], outputs=['y'], value=tensor_value, ) y = np.zeros(x, dtype=np.int32) expect(node, inputs=[x], outputs=[y], name='test_constantofshape_int_zeros') @staticmethod def export_int32_shape_zero(): # type: () -> None x = np.array([0, ]).astype(np.int64) tensor_value = onnx.helper.make_tensor("value", onnx.TensorProto.INT32, [1], [0]) node = onnx.helper.make_node( 'ConstantOfShape', inputs=['x'], outputs=['y'], value=tensor_value, ) y = np.zeros(x, dtype=np.int32) expect(node, inputs=[x], outputs=[y], name='test_constantofshape_int_shape_zero')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore from typing import Any, Tuple import onnx from ..base import Base from . import expect class RNN_Helper(): def __init__(self, **params): # type: (**Any) -> None # RNN Input Names X = str('X') W = str('W') R = str('R') B = str('B') H_0 = str('initial_h') required_inputs = [X, W, R] for i in required_inputs: assert i in params, "Missing Required Input: {0}".format(i) self.num_directions = params[str(W)].shape[0] if self.num_directions == 1: for k in params.keys(): if k != X: params[k] = np.squeeze(params[k], axis=0) hidden_size = params[R].shape[-1] batch_size = params[X].shape[1] b = params[B] if B in params else np.zeros(2 * hidden_size, dtype=np.float32) h_0 = params[H_0] if H_0 in params else np.zeros((batch_size, hidden_size), dtype=np.float32) self.X = params[X] self.W = params[W] self.R = params[R] self.B = b self.H_0 = h_0 else: raise NotImplementedError() def f(self, x): # type: (np.ndarray) -> np.ndarray return np.tanh(x) def step(self): # type: () -> Tuple[np.ndarray, np.ndarray] h_list = [] H_t = self.H_0 for x in np.split(self.X, self.X.shape[0], axis=0): H = self.f(np.dot(x, np.transpose(self.W)) + np.dot(H_t, np.transpose(self.R)) + np.add( *np.split(self.B, 2))) h_list.append(H) H_t = H concatenated = np.concatenate(h_list) if self.num_directions == 1: output = np.expand_dims(concatenated, 1) return output, h_list[-1] class RNN(Base): @staticmethod def export_defaults(): # type: () -> None input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32) input_size = 2 hidden_size = 4 weight_scale = 0.1 node = onnx.helper.make_node( 'RNN', inputs=['X', 'W', 'R'], outputs=['', 'Y'], hidden_size=hidden_size ) W = weight_scale * np.ones((1, hidden_size, input_size)).astype(np.float32) R = weight_scale * np.ones((1, hidden_size, hidden_size)).astype(np.float32) rnn = RNN_Helper(X=input, W=W, R=R) _, Y_h = rnn.step() expect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_simple_rnn_defaults') @staticmethod def export_initial_bias(): # type: () -> None input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32) input_size = 3 hidden_size = 5 custom_bias = 0.1 weight_scale = 0.1 node = onnx.helper.make_node( 'RNN', inputs=['X', 'W', 'R', 'B'], outputs=['', 'Y'], hidden_size=hidden_size ) W = weight_scale * np.ones((1, hidden_size, input_size)).astype(np.float32) R = weight_scale * np.ones((1, hidden_size, hidden_size)).astype(np.float32) # Adding custom bias W_B = custom_bias * np.ones((1, hidden_size)).astype(np.float32) R_B = np.zeros((1, hidden_size)).astype(np.float32) B = np.concatenate((W_B, R_B), axis=1) rnn = RNN_Helper(X=input, W=W, R=R, B=B) _, Y_h = rnn.step() expect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_simple_rnn_with_initial_bias') @staticmethod def export_seq_length(): # type: () -> None input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]], [[10., 11., 12.], [13., 14., 15.], [16., 17., 18.]]]).astype(np.float32) input_size = 3 hidden_size = 5 node = onnx.helper.make_node( 'RNN', inputs=['X', 'W', 'R', 'B'], outputs=['', 'Y'], hidden_size=hidden_size ) W = np.random.randn(1, hidden_size, input_size).astype(np.float32) R = np.random.randn(1, hidden_size, hidden_size).astype(np.float32) # Adding custom bias W_B = np.random.randn(1, hidden_size).astype(np.float32) R_B = np.random.randn(1, hidden_size).astype(np.float32) B = np.concatenate((W_B, R_B), axis=1) rnn = RNN_Helper(X=input, W=W, R=R, B=B) _, Y_h = rnn.step() expect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_rnn_seq_length')
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class ReduceLogSumExp(Base): @staticmethod def export_do_not_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 0 node = onnx.helper.make_node( 'ReduceLogSumExp', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims ) data = np.array( [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.log(np.sum( np.exp(data), axis=tuple(axes), keepdims=keepdims == 1)) # print(reduced) #[[20., 2.31326175] # [40.00004578, 2.31326175] # [60.00671387, 2.31326175]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_log_sum_exp_do_not_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.log(np.sum( np.exp(data), axis=tuple(axes), keepdims=keepdims == 1)) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_log_sum_exp_do_not_keepdims_random') @staticmethod def export_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 1 node = onnx.helper.make_node( 'ReduceLogSumExp', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims ) data = np.array( [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.log(np.sum(np.exp(data), axis=tuple(axes), keepdims=keepdims == 1)) # print(reduced) # [[[20., 2.31326175]] # [[40.00004578, 2.31326175]] # [[60.00671387, 2.31326175]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_log_sum_exp_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.log(np.sum(np.exp(data), axis=tuple(axes), keepdims=keepdims == 1)) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_log_sum_exp_keepdims_random') @staticmethod def export_default_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = None keepdims = 1 node = onnx.helper.make_node( 'ReduceLogSumExp', inputs=['data'], outputs=['reduced'], keepdims=keepdims ) data = np.array( [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.log(np.sum(np.exp(data), axis=axes, keepdims=keepdims == 1)) # print(reduced) # [[[60.00671387]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_log_sum_exp_default_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.log(np.sum(np.exp(data), axis=axes, keepdims=keepdims == 1)) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_log_sum_exp_default_axes_keepdims_random') @staticmethod def export_negative_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [-2] keepdims = 1 node = onnx.helper.make_node( 'ReduceLogSumExp', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims ) data = np.array( [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.log(np.sum(np.exp(data), axis=tuple(axes), keepdims=keepdims == 1)) # print(reduced) # [[[20., 2.31326175]] # [[40.00004578, 2.31326175]] # [[60.00671387, 2.31326175]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_log_sum_exp_negative_axes_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.log(np.sum(np.exp(data), axis=tuple(axes), keepdims=keepdims == 1)) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_log_sum_exp_negative_axes_keepdims_random')