test_forward.py 75.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
17 18
import numpy as np
import math
Zhi committed
19 20
import torch
import torchvision
21 22 23 24 25
import topi
import topi.testing
import tvm
from tvm import relay
from tvm.contrib import graph_runtime
26
from tvm.relay.testing.config import ctx_list
27
import onnx
28
from onnx import helper, TensorProto, mapping
29
import scipy
30

31 32

def get_tvm_output(graph_def, input_data, target, ctx, output_shape=None, output_dtype='float32', opset=None):
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    """ Generic function to execute and get tvm output"""
    target = 'llvm'
    if isinstance(input_data, list):
        input_names = {}
        shape_dict = {}
        dtype_dict = {}
        for i, _ in enumerate(input_data):
            input_names[i] = graph_def.graph.input[i].name
            shape_dict[input_names[i]] = input_data[i].shape
            dtype_dict[input_names[i]] = input_data[i].dtype
    else:
        input_names = graph_def.graph.input[0].name
        shape_dict = {input_names: input_data.shape}
        dtype_dict = {input_names: input_data.dtype}

48
    mod, params = relay.frontend.from_onnx(graph_def, shape_dict, opset=opset)
49
    with relay.build_config(opt_level=1):
50
        graph, lib, params = relay.build(mod,
51 52
                                         target,
                                         params=params)
53 54 55 56 57 58

    ctx = tvm.cpu(0)
    m = graph_runtime.create(graph, lib, ctx)
    # set inputs
    if isinstance(input_data, list):
        for i, e in enumerate(input_names):
59 60
            m.set_input(input_names[i], tvm.nd.array(
                input_data[i].astype(input_data[i].dtype)))
61
    else:
62 63
        m.set_input(input_names, tvm.nd.array(
            input_data.astype(input_data.dtype)))
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

    m.set_input(**params)
    # execute
    m.run()
    # get outputs
    if isinstance(output_shape, list) and isinstance(output_dtype, list):
        tvm_output_list = []
        for i, _ in enumerate(output_shape):
            tvm_output = m.get_output(i)
            tvm_output_list.append(tvm_output.asnumpy())
        return tvm_output_list
    else:
        tvm_output = m.get_output(0)
        return tvm_output.asnumpy()

79

80
def get_onnxruntime_output(model, inputs, dtype='float32'):
81 82
    import onnxruntime.backend
    rep = onnxruntime.backend.prepare(model, 'CPU')
83 84 85 86 87
    if isinstance(inputs, list) and len(inputs) > 1:
        ort_out = rep.run(inputs)
    else:
        x = inputs.astype(dtype)
        ort_out = rep.run(x)[0]
88
    return ort_out
89 90 91 92 93 94


def verify_onnx_forward_impl(graph_file, data_shape, out_shape):
    dtype = 'float32'
    x = np.random.uniform(size=data_shape)
    model = onnx.load_model(graph_file)
95
    c2_out = get_onnxruntime_output(model, x, dtype)
96 97 98 99
    for target, ctx in ctx_list():
        tvm_out = get_tvm_output(model, x, target, ctx, out_shape, dtype)
        tvm.testing.assert_allclose(c2_out, tvm_out, rtol=1e-5, atol=1e-5)

100

101
def verify_super_resolution_example():
102 103 104
    verify_onnx_forward_impl(
        super_resolution, (1, 1, 224, 224), (1, 1, 672, 672))

105 106 107 108

def verify_squeezenet1_1():
    verify_onnx_forward_impl(squeezenet1_1, (1, 3, 224, 224), (1, 1000))

109

110 111 112
def verify_lenet():
    verify_onnx_forward_impl(lenet, (1, 1, 28, 28), (1, 10))

113

114 115 116 117 118 119 120 121 122 123
def verify_resnet18():
    verify_onnx_forward_impl(resnet18_1_0, (1, 3, 224, 224), (1, 1000))


def test_reshape():
    in_shape = (4, 3, 3, 4)
    ref_shape = (6, 2, 4, 3)

    ref_array = np.array(ref_shape)
    ref_node = onnx.helper.make_node('Constant',
124 125 126 127 128 129
                                     inputs=[],
                                     outputs=['ref_in'],
                                     value=onnx.helper.make_tensor(name='const_tensor',
                                                                   data_type=onnx.TensorProto.INT32,
                                                                   dims=ref_array.shape,
                                                                   vals=ref_array.flatten().astype(int)))
130 131 132 133
    reshape_node = helper.make_node("Reshape", ["in", "ref_in"], ["out"])

    graph = helper.make_graph([ref_node, reshape_node],
                              "reshape_test",
134 135 136 137
                              inputs=[helper.make_tensor_value_info("in",
                                                                    TensorProto.FLOAT, list(in_shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(ref_shape))])
138 139 140 141 142 143 144 145 146

    model = helper.make_model(graph, producer_name='reshape_test')

    for target, ctx in ctx_list():
        x = np.random.uniform(size=in_shape).astype('int32')
        tvm_out = get_tvm_output(model, x, target, ctx, ref_shape, 'float32')

    tvm.testing.assert_allclose(ref_shape, tvm_out.shape)

147

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
def test_expand():

    def _test_expand(name, data, shape, ref_data):
        shape_array = np.array(shape)
        shape_node = onnx.helper.make_node('Constant',
                                    inputs=[],
                                    outputs=['shape'],
                                    value=onnx.helper.make_tensor(name = 'const_tensor',
                                                                  data_type = onnx.TensorProto.INT32,
                                                                  dims = shape_array.shape,
                                                                  vals = shape_array.flatten().astype('int32')))
        expand_node = helper.make_node("Expand", ["in", "shape"], ["out"])

        graph = helper.make_graph([shape_node, expand_node],
                                "expand_test",
                                inputs = [helper.make_tensor_value_info("in",
                                                TensorProto.FLOAT, list(data.shape))],
                                outputs = [helper.make_tensor_value_info("out",
                                                TensorProto.FLOAT, list(ref_data.shape))])

        model = helper.make_model(graph, producer_name=name)

        for target, ctx in ctx_list():
            tvm_out = get_tvm_output(model, data, target, ctx, ref_data.shape, 'float32')

        tvm.testing.assert_allclose(ref_data, tvm_out)

    in_shape = (3, 1)
    shape = (3, 4)
    data = np.random.uniform(size=in_shape).astype(np.float32)
    ref_data = np.tile(data, 4)
    _test_expand('expand_with_dim_unchanged_test', data, shape, ref_data)

    in_shape = (3, 1)
    shape = (2, 1, 6)
    data = np.random.uniform(size=in_shape).astype(np.float32)
    ref_data = data * np.ones(shape, dtype=np.float32)
    _test_expand('expand_with_dim_changed_test', data, shape, ref_data)


188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
def verify_depth_to_space(inshape, outshape, mode, blockSize):
    node = onnx.helper.make_node('DepthToSpace',
                                 inputs=['x'],
                                 outputs=['y'],
                                 blocksize=blockSize)

    graph = helper.make_graph([node],
                              "depth_to_space_test",
                              inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(inshape))],
                              outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(outshape))])

    model = helper.make_model(graph, producer_name='depth_to_space_test')

    for target, ctx in ctx_list():
        x = np.random.uniform(size=inshape).astype('float32')
        tvm_out = get_tvm_output(model, x, target, ctx, outshape, 'float32')
        onnx_out = get_onnxruntime_output(model, x, 'float32')
        tvm.testing.assert_allclose(onnx_out, tvm_out)


def test_depth_to_space():
    # current onnx.checker use OpSet-1 version of DepthToSpace, which doesn't have a mode argument.
    # TO-DO, we can add mode arguement to test CRD mode and DCR mode
    # in the future when we update to a newer onnx version.
    verify_depth_to_space((1, 8, 2, 3), (1, 2, 4, 6), mode="CRD", blockSize=2)


def verify_space_to_depth(inshape, outshape, blockSize):
    node = onnx.helper.make_node('SpaceToDepth',
                                 inputs=['x'],
                                 outputs=['y'],
                                 blocksize=blockSize)

    graph = helper.make_graph([node],
                              "space_to_depth_test",
                              inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(inshape))],
                              outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(outshape))])

    model = helper.make_model(graph, producer_name='space_to_depth_test')

    for target, ctx in ctx_list():
        x = np.random.uniform(size=inshape).astype('float32')
        tvm_out = get_tvm_output(model, x, target, ctx, outshape, 'float32')
        onnx_out = get_onnxruntime_output(model, x, 'float32')
        tvm.testing.assert_allclose(onnx_out, tvm_out)


def test_space_to_depth():
    verify_space_to_depth((1, 1, 4, 6), (1, 4, 2, 3), 2)


239
def test_shape():
240
    in_shape = (4, 3, 3, 4)
241
    ref_shape = (6, 2, 4, 3)
242

243
    ref_array = np.array(ref_shape)
244
    ref_node = onnx.helper.make_node('Constant',
245 246 247 248 249 250
                                     inputs=[],
                                     outputs=['ref_in'],
                                     value=onnx.helper.make_tensor(name='const_tensor',
                                                                   data_type=onnx.TensorProto.INT32,
                                                                   dims=ref_array.shape,
                                                                   vals=ref_array.flatten().astype(int)))
251 252 253
    reshape_node = helper.make_node("Reshape", ["in", "ref_in"], ["out"])

    shape_node = helper.make_node("Shape", ['out'], ['final_out'])
254

255 256
    graph = helper.make_graph([ref_node, reshape_node, shape_node],
                              "shape_test",
257 258 259 260
                              inputs=[helper.make_tensor_value_info("in",
                                                                    TensorProto.FLOAT, list(in_shape))],
                              outputs=[helper.make_tensor_value_info("final_out",
                                                                     TensorProto.FLOAT, list(ref_shape))])
261

262
    model = helper.make_model(graph, producer_name='shape_test')
263 264

    for target, ctx in ctx_list():
265 266
        x = np.random.uniform(size=in_shape).astype('int32')
        tvm_out = get_tvm_output(model, x, target, ctx, ref_shape, 'int32')
267

268
    tvm.testing.assert_allclose(ref_shape, tvm_out)
269

270

271 272 273 274 275 276 277 278 279 280 281 282 283
def _test_power_iteration(x_shape, y_shape):
    if isinstance(y_shape, int):
        y_shape = [y_shape]

    x = np.random.uniform(size=x_shape).astype(np.float32)
    y = np.random.uniform(size=y_shape).astype(np.float32)

    np_res = np.power(x, y).astype(np.float32)

    res = helper.make_node("Pow", ['x', 'y'], ['out'])

    graph = helper.make_graph([res],
                              'power_test',
284 285 286 287 288 289
                              inputs=[helper.make_tensor_value_info("x",
                                                                    TensorProto.FLOAT, list(x_shape)),
                                      helper.make_tensor_value_info("y",
                                                                    TensorProto.FLOAT, list(y_shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(np_res.shape))])
290 291 292 293 294 295 296

    model = helper.make_model(graph, producer_name='power_test')

    for target, ctx in ctx_list():
        tvm_out = get_tvm_output(model, [x, y], target, ctx, np_res.shape)
        tvm.testing.assert_allclose(np_res, tvm_out, rtol=1e-5, atol=1e-5)

297

298 299 300 301 302
def test_power():
    _test_power_iteration((1, 3), (1))
    _test_power_iteration((2, 3), (2, 3))
    _test_power_iteration((2, 3), (1, 3))

303

304 305 306 307 308 309 310
def test_squeeze():
    in_shape = (1, 3, 1, 3, 1, 1)
    out_shape = (3, 3)
    y = helper.make_node("Squeeze", ['in'], ['out'], axes=[0, 2, 4, 5])

    graph = helper.make_graph([y],
                              'squeeze_test',
311 312 313 314
                              inputs=[helper.make_tensor_value_info("in",
                                                                    TensorProto.FLOAT, list(in_shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(out_shape))])
315 316 317 318 319 320 321 322 323

    model = helper.make_model(graph, producer_name='squeeze_test')

    for target, ctx in ctx_list():
        x = np.random.uniform(size=in_shape).astype('float32')
        tvm_out = get_tvm_output(model, x, target, ctx, out_shape, 'float32')

    tvm.testing.assert_allclose(out_shape, tvm_out.shape)

324

325 326 327 328 329 330
def test_flatten():

    in_shape = (1, 3, 4, 4)
    axis = 1
    ref_shape = (1, 48)

331
    flatten_node = helper.make_node("Flatten", ["in"], ["out"], axis=axis)
332 333 334

    graph = helper.make_graph([flatten_node],
                              "flatten_test",
335 336 337 338
                              inputs=[helper.make_tensor_value_info("in",
                                                                    TensorProto.FLOAT, list(in_shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(ref_shape))])
339 340 341 342 343 344 345 346 347

    model = helper.make_model(graph, producer_name='flatten_test')

    for target, ctx in ctx_list():
        x = np.random.uniform(size=in_shape).astype('int32')
        tvm_out = get_tvm_output(model, x, target, ctx, ref_shape, 'float32')

    tvm.testing.assert_allclose(ref_shape, tvm_out.shape)

348

349 350 351 352 353 354 355 356
def test_unsqueeze():
    in_shape = (3, 3)
    axis = (0, 3, 4)
    out_shape = (1, 3, 3, 1, 1)
    y = helper.make_node("Unsqueeze", ['in'], ['out'], axes=list(axis))

    graph = helper.make_graph([y],
                              'squeeze_test',
357 358 359 360
                              inputs=[helper.make_tensor_value_info("in",
                                                                    TensorProto.FLOAT, list(in_shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(out_shape))])
361 362 363 364 365 366 367 368 369

    model = helper.make_model(graph, producer_name='squeeze_test')

    for target, ctx in ctx_list():
        x = np.random.uniform(size=in_shape).astype('float32')
        tvm_out = get_tvm_output(model, x, target, ctx, out_shape, 'float32')

    tvm.testing.assert_allclose(out_shape, tvm_out.shape)

370

371 372 373 374 375 376 377 378 379
def verify_gather(in_shape, indices, axis, dtype):
    x = np.random.uniform(size=in_shape).astype(dtype)
    indices = np.array(indices, dtype="int32")
    out_np = np.take(x, indices, axis=axis)

    y = helper.make_node("Gather", ['in', 'indices'], ['out'], axis=axis)

    graph = helper.make_graph([y],
                              'gather_test',
380 381 382 383 384 385
                              inputs=[helper.make_tensor_value_info("in",
                                                                    TensorProto.FLOAT, list(in_shape)),
                                      helper.make_tensor_value_info("indices",
                                                                    TensorProto.INT32, list(indices.shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(out_np.shape))])
386 387 388
    model = helper.make_model(graph, producer_name='gather_test')

    for target, ctx in ctx_list():
389 390
        tvm_out = get_tvm_output(
            model, [x, indices], target, ctx, out_np.shape)
391 392
        tvm.testing.assert_allclose(out_np, tvm_out)

393

394 395
def test_gather():
    verify_gather((4,), [1], 0, 'int32')
396 397 398 399 400 401
    verify_gather((1, 4), [0], 0, 'int32')
    verify_gather((4,), [[[1, 0], [0, 1]]], 0, 'float32')
    verify_gather((2, 2), [[[1, 0], [0, 1]]], 1, 'int32')
    verify_gather((3, 3, 3), [[[1, 0]]], -1, 'int32')
    verify_gather((4, 3, 5, 6), [[2, 1, 0, 0]], 0, 'float32')

402

403
def _test_slice_iteration_v1(indata, outdata, starts, ends, axes=None):
404
    if axes:
405 406
        y = helper.make_node(
            "Slice", ['in'], ['out'], axes=axes, starts=starts, ends=ends)
407
    else:
408 409
        y = helper.make_node(
            "Slice", ['in'], ['out'], starts=starts, ends=ends)
410 411 412

    graph = helper.make_graph([y],
                              'slice_test',
413 414 415 416
                              inputs=[helper.make_tensor_value_info("in",
                                                                    TensorProto.FLOAT, list(indata.shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(outdata.shape))])
417 418 419 420

    model = helper.make_model(graph, producer_name='slice_test')

    for target, ctx in ctx_list():
421 422
        tvm_out = get_tvm_output(
            model, indata, target, ctx, outdata.shape, 'float32', opset=1)
423 424 425

    tvm.testing.assert_allclose(outdata, tvm_out)

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485

def _test_slice_iteration_v10(indata, outdata, starts, ends, axes=None):
    if isinstance(starts, int):
        starts = (starts, )
    if isinstance(ends, int):
        ends = (ends, )
    if isinstance(axes, int):
        axes = (axes, )
    starts = np.asarray(starts)
    ends = np.asarray(ends)
    inputs = [
        helper.make_tensor_value_info("data", TensorProto.FLOAT,
                                      list(indata.shape)),
        helper.make_tensor_value_info("starts", TensorProto.INT32,
                                      list(starts.shape)),
        helper.make_tensor_value_info("ends", TensorProto.INT32,
                                      list(ends.shape))
    ]
    initializer = [
        helper.make_tensor("starts", TensorProto.INT32, list(starts.shape),
                           starts),
        helper.make_tensor("ends", TensorProto.INT32, list(ends.shape), ends)
    ]

    if axes:
        axes = np.asarray(axes)
        y = helper.make_node("Slice", ["data", "starts", "ends", "axes"],
                             ["out"])
        inputs.append(
            helper.make_tensor_value_info("axes", TensorProto.INT32,
                                          list(axes.shape)))
        initializer.append(
            helper.make_tensor("axes", TensorProto.INT32, list(axes.shape),
                               axes))
    else:
        y = helper.make_node("Slice", ["data", "starts", "ends"], ["out"])

    graph = helper.make_graph([y],
                              'slice_test',
                              inputs=inputs,
                              outputs=[
                                  helper.make_tensor_value_info(
                                      "out", TensorProto.FLOAT,
                                      list(outdata.shape))
                              ],
                              initializer=initializer)
    model = helper.make_model(graph, producer_name='slice_test')

    for target, ctx in ctx_list():
        tvm_out = get_tvm_output(model,
                                 indata,
                                 target,
                                 ctx,
                                 outdata.shape,
                                 'float32',
                                 opset=10)

    tvm.testing.assert_allclose(outdata, tvm_out)


486 487
def test_slice():
    x = np.random.randn(20, 10, 5).astype(np.float32)
488 489 490 491 492 493 494 495 496
    _test_slice_iteration_v1(x, x[0:3, 0:10], (0, 0), (3, 10), (0, 1))
    _test_slice_iteration_v1(x, x[:, :, 3:4], (0, 0, 3), (20, 10, 4))
    _test_slice_iteration_v1(x, x[:, 1:1000], (1), (1000), (1))
    _test_slice_iteration_v1(x, x[:, 0:-1], (0), (-1), (1))
    _test_slice_iteration_v10(x, x[0:3, 0:10], (0, 0), (3, 10), (0, 1))
    _test_slice_iteration_v10(x, x[:, :, 3:4], (0, 0, 3), (20, 10, 4))
    _test_slice_iteration_v10(x, x[:, 1:1000], (1), (1000), (1))
    _test_slice_iteration_v10(x, x[:, 0:-1], (0), (-1), (1))

497 498 499 500 501 502 503 504 505

def _test_onnx_op_elementwise(inshape, outfunc, npargs, dtype, opname, kwargs):
    indata = np.random.uniform(-1, 1, size=inshape).astype(dtype)
    outdata = outfunc(indata, **npargs)

    y = helper.make_node(opname, ['in'], ['out'], **kwargs)

    graph = helper.make_graph([y],
                              opname+'_test',
506 507 508 509
                              inputs=[helper.make_tensor_value_info("in",
                                                                    TensorProto.FLOAT, list(indata.shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(outdata.shape))])
510 511 512 513

    model = helper.make_model(graph, producer_name=opname+'_test')

    for target, ctx in ctx_list():
514 515
        tvm_out = get_tvm_output(
            model, indata, target, ctx, outdata.shape, dtype)
516 517 518

    tvm.testing.assert_allclose(outdata, tvm_out)

519

520
def test_floor():
521 522 523
    _test_onnx_op_elementwise((2, 4, 5, 6), np.floor,
                              {}, 'float32', 'Floor', {})

524 525 526 527

def test_ceil():
    _test_onnx_op_elementwise((2, 4, 5, 6), np.ceil, {}, 'float32', 'Ceil', {})

528

529 530 531 532 533 534 535 536
def test_clip():
    _test_onnx_op_elementwise((2, 4, 5, 6),
                              np.clip,
                              {'a_min': -1.0, 'a_max': 1.0},
                              'float32',
                              'Clip',
                              {'min': -1.0, 'max': 1.0})

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568

def test_onehot():
    indices_shape = [10]
    indices_array = np.random.randint(
        low=0, high=9, size=indices_shape, dtype='int32')
    depth = 10
    values = np.asarray([0, 1])
    out_np = np.eye(depth)[indices_array.reshape(-1)]

    onehot_node = helper.make_node(
        "OneHot", ["indices", "depth", "values"], ["out"])

    graph = helper.make_graph([onehot_node],
                              "onehot_test",
                              inputs=[helper.make_tensor_value_info("indices",
                                                                    TensorProto.INT32, indices_shape),
                                      helper.make_tensor_value_info("depth",
                                                                    TensorProto.INT32, [1]),
                                      helper.make_tensor_value_info("values",
                                                                    TensorProto.INT32, values.shape)],
                              initializer=[helper.make_tensor("depth", TensorProto.INT32, [1], [depth]),
                                           helper.make_tensor("values", TensorProto.INT32, values.shape, values)],
                              outputs=[helper.make_tensor_value_info("out", TensorProto.INT32, out_np.shape)])

    model = helper.make_model(graph, producer_name="onehot_test")

    for target, ctx in ctx_list():
        tvm_out = get_tvm_output(
            model, [indices_array], target, ctx, out_np.shape)
        tvm.testing.assert_allclose(out_np, tvm_out, rtol=1e-5, atol=1e-5)


569 570 571 572 573 574 575 576 577 578 579 580
def test_matmul():
    a_shape = (4, 3)
    b_shape = (3, 4)

    a_array = np.random.uniform(size=a_shape).astype('float32')
    b_array = np.random.uniform(size=b_shape).astype('float32')
    out_np = np.matmul(a_array, b_array)

    mul_node = helper.make_node("MatMul", ["a", "b"], ["out"])

    graph = helper.make_graph([mul_node],
                              "matmul_test",
581 582 583 584 585 586 587 588 589 590 591 592 593 594
                              inputs=[helper.make_tensor_value_info("a",
                                                                    TensorProto.FLOAT, list(a_shape)),
                                      helper.make_tensor_value_info("b",
                                                                    TensorProto.FLOAT, list(b_shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(out_np.shape))])

    model = helper.make_model(graph, producer_name='matmul_test')

    for target, ctx in ctx_list():
        tvm_out = get_tvm_output(
            model, [a_array, b_array], target, ctx, out_np.shape)
        tvm.testing.assert_allclose(out_np, tvm_out, rtol=1e-5, atol=1e-5)

595
def verify_batch_matmul(a_shape, b_shape):
596 597 598 599 600 601 602 603 604 605 606 607 608 609
    a_array = np.random.uniform(size=a_shape).astype('float32')
    b_array = np.random.uniform(size=b_shape).astype('float32')
    out_np = np.matmul(a_array, b_array)

    mul_node = helper.make_node("MatMul", ["a", "b"], ["out"])

    graph = helper.make_graph([mul_node],
                              "matmul_test",
                              inputs=[helper.make_tensor_value_info("a",
                                                                    TensorProto.FLOAT, list(a_shape)),
                                      helper.make_tensor_value_info("b",
                                                                    TensorProto.FLOAT, list(b_shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(out_np.shape))])
610 611 612 613

    model = helper.make_model(graph, producer_name='matmul_test')

    for target, ctx in ctx_list():
614 615
        tvm_out = get_tvm_output(
            model, [a_array, b_array], target, ctx, out_np.shape)
616 617
        tvm.testing.assert_allclose(out_np, tvm_out, rtol=1e-5, atol=1e-5)

618 619 620 621
def test_batch_matmul():
    verify_batch_matmul((2, 3, 4, 3), (2, 3, 3, 4))
    verify_batch_matmul((2, 4, 3), (3, 4))
    verify_batch_matmul((2, 3, 4, 3), (3, 4))
622

623 624 625
def verify_lrn(shape, nsize, dtype, alpha=None, beta=None, bias=None):
    in_array = np.random.uniform(size=shape).astype(dtype)

626
    if alpha == None and beta == None and bias == None:
627 628 629
        alpha = 0.0001
        beta = 0.75
        bias = 1.0
630 631
        node = onnx.helper.make_node(
            'LRN', inputs=['in'], outputs=['out'], size=nsize)
632 633 634 635 636 637
    else:
        node = onnx.helper.make_node('LRN', inputs=['in'], outputs=['out'], alpha=alpha,
                                     beta=beta, bias=bias, size=nsize)

    graph = helper.make_graph([node],
                              "lrn_test",
638 639 640
                              inputs=[helper.make_tensor_value_info(
                                  "in", TensorProto.FLOAT, list(shape))],
                              outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(shape))])
641 642 643 644 645 646
    model = helper.make_model(graph, producer_name='lrn_test')

    def _get_python_lrn():
        square_sum = np.zeros(shape).astype(dtype)
        for n, c, h, w in np.ndindex(in_array.shape):
            square_sum[n, c, h, w] = sum(in_array[n,
647 648 649 650
                                                  max(0, c - int(math.floor((nsize - 1) / 2))):
                                                  min(5, c + int(math.ceil((nsize - 1) / 2)) + 1),
                                                  h,
                                                  w] ** 2)
651 652 653 654 655 656
        py_out = in_array / ((bias + (alpha / nsize) * square_sum) ** beta)
        return py_out

    for target, ctx in ctx_list():
        input_name = model.graph.input[0].name
        py_out = _get_python_lrn()
657 658
        tvm_out = get_tvm_output(
            model, in_array, target, ctx, py_out.shape, 'float32')
659 660 661 662 663 664 665
        tvm.testing.assert_allclose(py_out, tvm_out, rtol=1e-5, atol=1e-5)


def test_lrn():
    verify_lrn((5, 5, 5, 5), 3, 'float32')
    verify_lrn((5, 5, 5, 5), 3, 'float32', alpha=0.0002, beta=0.5, bias=2.0)

666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685

def verify_instance_norm(shape, axis=1):

    def _get_python_instance_norm(x, gamma, beta, epsilon=1e-5):
        dims_x = len(x.shape)
        axis = tuple(range(2, dims_x))
        mean = np.mean(x, axis=axis, keepdims=True)
        var = np.var(x, axis=axis, keepdims=True)
        dim_ones = (1,) * (dims_x - 2)
        gamma = gamma.reshape(-1, *dim_ones)
        beta = beta.reshape(-1, *dim_ones)
        return gamma * (x - mean) / np.sqrt(var + epsilon) + beta

    x = np.random.randn(*shape).astype(np.float32)
    gamma = np.random.randn(shape[1]).astype(np.float32)
    beta = np.random.randn(shape[1]).astype(np.float32)
    epsilon = 1e-5
    y = _get_python_instance_norm(x, gamma, beta, epsilon).astype(np.float32)

    node = onnx.helper.make_node(
686 687 688 689 690
        'InstanceNormalization',
        inputs=['x', 'gamma', 'beta'],
        outputs=['y'],
        epsilon=epsilon,
    )
691 692 693
    graph = helper.make_graph([node],
                              "instance_norm_test",
                              inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(shape)),
694 695
                                      helper.make_tensor_value_info(
                                          "gamma", TensorProto.FLOAT, (shape[1],)),
696 697 698 699
                                      helper.make_tensor_value_info("beta", TensorProto.FLOAT, (shape[1],))],
                              outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(shape))])
    model = helper.make_model(graph, producer_name='instance_norm_test')
    for target, ctx in ctx_list():
700 701
        tvm_out = get_tvm_output(
            model, [x, gamma, beta], target, ctx, shape, 'float32')
702 703 704 705 706 707 708 709 710 711
        tvm.testing.assert_allclose(y, tvm_out, rtol=1e-5, atol=1e-5)


def test_instance_norm():
    verify_instance_norm((2, 3, 4, 5))
    verify_instance_norm((32, 64, 80, 64))
    verify_instance_norm((8, 6, 5))
    verify_instance_norm((8, 7, 6, 5, 4))


712 713 714 715
def _test_upsample_nearest():
    scale = 2
    in_shape = (1, 1, 3, 3)
    out_shape = (1, 1, 3*scale, 3*scale)
716 717
    y = helper.make_node("Upsample", ['in'], [
                         'out'], mode='nearest', scales=[1.0, 1.0, 2.0, 2.0])
718 719

    in_array = np.random.uniform(size=in_shape).astype(np.float32)
720 721
    out_array = topi.testing.upsampling_python(
        in_array, (scale, scale), "NCHW")
722 723 724

    graph = helper.make_graph([y],
                              'upsample_nearest_test',
725 726 727
                              inputs=[helper.make_tensor_value_info(
                                  "in", TensorProto.FLOAT, list(in_shape))],
                              outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))])
728 729 730 731

    model = helper.make_model(graph, producer_name='upsample_nearest_test')

    for target, ctx in ctx_list():
732 733
        tvm_out = get_tvm_output(
            model, in_array, target, ctx, out_shape, 'float32')
734 735
        tvm.testing.assert_allclose(out_array, tvm_out)

736

737 738 739 740
def _test_upsample_bilinear():
    scale = 2
    in_shape = (1, 1, 3, 3)
    out_shape = (1, 1, 3*scale, 3*scale)
741 742
    y = helper.make_node("Upsample", ['in'], [
                         'out'], mode='linear', scales=[1.0, 1.0, 2.0, 2.0])
743 744

    in_array = np.random.uniform(size=in_shape).astype(np.float32)
745 746
    out_array = topi.testing.bilinear_resize_python(
        in_array, (3*scale, 3*scale), "NCHW")
747 748 749

    graph = helper.make_graph([y],
                              'upsample_bilinear_test',
750 751 752
                              inputs=[helper.make_tensor_value_info(
                                  "in", TensorProto.FLOAT, list(in_shape))],
                              outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))])
753 754 755 756

    model = helper.make_model(graph, producer_name='upsample_bilinear_test')

    for target, ctx in ctx_list():
757 758
        tvm_out = get_tvm_output(
            model, in_array, target, ctx, out_shape, 'float32')
759 760
        tvm.testing.assert_allclose(out_array, tvm_out, rtol=1e-5, atol=1e-5)

761

762 763 764 765
def _test_upsample_bilinear_opset9():
    scale = 2
    in_shape = (1, 1, 3, 3)
    out_shape = (1, 1, 3*scale, 3*scale)
766 767
    y = helper.make_node("Upsample", ['in', 'scales'], ['out'], mode='linear')
    scales = [1.0, 1.0, 2.0, 2.0]
768
    in_array = np.random.uniform(size=in_shape).astype(np.float32)
769 770
    out_array = topi.testing.bilinear_resize_python(
        in_array, (3*scale, 3*scale), "NCHW")
771 772 773

    ref_array = np.array(scales)
    ref_node = helper.make_node('Constant',
774 775 776 777 778 779
                                inputs=[],
                                outputs=['scales'],
                                value=onnx.helper.make_tensor(name='const_tensor',
                                                              data_type=TensorProto.FLOAT,
                                                              dims=ref_array.shape,
                                                              vals=ref_array.flatten().astype(float)))
780 781 782

    graph = helper.make_graph([ref_node, y],
                              'upsample_bilinear_opset9_test',
783 784 785
                              inputs=[helper.make_tensor_value_info(
                                  "in", TensorProto.FLOAT, list(in_shape))],
                              outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))])
786

787 788
    model = helper.make_model(
        graph, producer_name='upsample_bilinear_opset9_test')
789 790

    for target, ctx in ctx_list():
791 792
        tvm_out = get_tvm_output(
            model, in_array, target, ctx, out_shape, 'float32')
793 794
        tvm.testing.assert_allclose(out_array, tvm_out, rtol=1e-5, atol=1e-5)

795

796 797 798
def test_upsample():
    _test_upsample_nearest()
    _test_upsample_bilinear()
799
    _test_upsample_bilinear_opset9()
800

801

802 803 804 805 806 807
def _test_softmax(inshape, axis):
    opname = 'Softmax'
    indata = np.random.uniform(size=inshape).astype(np.float32)
    outshape = inshape
    outdata = topi.testing.softmax_python(indata)
    if isinstance(axis, int):
808
        y = helper.make_node(opname, ['in'], ['out'], axis=axis)
809 810 811 812 813
    elif axis is None:
        y = helper.make_node(opname, ['in'], ['out'])

    graph = helper.make_graph([y],
                              opname+'_test',
814 815 816 817
                              inputs=[helper.make_tensor_value_info("in",
                                                                    TensorProto.FLOAT, list(indata.shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(outdata.shape))])
818 819 820 821

    model = helper.make_model(graph, producer_name=opname+'_test')

    for target, ctx in ctx_list():
822 823
        tvm_out = get_tvm_output(
            model, indata, target, ctx, outshape, 'float32')
824 825
        tvm.testing.assert_allclose(outdata, tvm_out, rtol=1e-5, atol=1e-5)

826

827 828 829 830
def test_softmax():
    _test_softmax((1, 10), None)
    _test_softmax((1, 10), 1)

831

832 833 834 835 836 837 838 839 840 841 842 843 844
def verify_min(input_dim):
    dtype = 'float32'

    a_np1 = np.random.uniform(size=input_dim).astype(dtype)
    a_np2 = np.random.uniform(size=input_dim).astype(dtype)
    a_np3 = np.random.uniform(size=input_dim).astype(dtype)

    b_np = np.min((a_np1, a_np2, a_np3), axis=0)

    min_node = helper.make_node("Min", ["a_np1", "a_np2", "a_np3"], ["out"])

    graph = helper.make_graph([min_node],
                              "Min_test",
845 846 847 848 849 850 851 852
                              inputs=[helper.make_tensor_value_info("a_np1",
                                                                    TensorProto.FLOAT, list(input_dim)),
                                      helper.make_tensor_value_info("a_np2",
                                                                    TensorProto.FLOAT, list(input_dim)),
                                      helper.make_tensor_value_info("a_np3",
                                                                    TensorProto.FLOAT, list(input_dim))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(b_np.shape))])
853 854 855 856

    model = helper.make_model(graph, producer_name='Min_test')

    for target, ctx in ctx_list():
857 858
        tvm_out = get_tvm_output(
            model, [a_np1, a_np2, a_np3], target, ctx, b_np.shape)
859 860
        tvm.testing.assert_allclose(b_np, tvm_out, rtol=1e-5, atol=1e-5)

861

862 863 864 865
def test_forward_min():
    verify_min((1, 3, 20, 20))
    verify_min((20, 20))

866

867 868 869 870 871 872 873 874 875 876 877 878 879
def verify_max(input_dim):
    dtype = 'float32'

    a_np1 = np.random.uniform(size=input_dim).astype(dtype)
    a_np2 = np.random.uniform(size=input_dim).astype(dtype)
    a_np3 = np.random.uniform(size=input_dim).astype(dtype)

    b_np = np.max((a_np1, a_np2, a_np3), axis=0)

    max_node = helper.make_node("Max", ["a_np1", "a_np2", "a_np3"], ["out"])

    graph = helper.make_graph([max_node],
                              "Max_test",
880 881 882 883 884 885 886 887
                              inputs=[helper.make_tensor_value_info("a_np1",
                                                                    TensorProto.FLOAT, list(input_dim)),
                                      helper.make_tensor_value_info("a_np2",
                                                                    TensorProto.FLOAT, list(input_dim)),
                                      helper.make_tensor_value_info("a_np3",
                                                                    TensorProto.FLOAT, list(input_dim))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(b_np.shape))])
888 889 890 891

    model = helper.make_model(graph, producer_name='Max_test')

    for target, ctx in ctx_list():
892 893
        tvm_out = get_tvm_output(
            model, [a_np1, a_np2, a_np3], target, ctx, b_np.shape)
894 895
        tvm.testing.assert_allclose(b_np, tvm_out, rtol=1e-5, atol=1e-5)

896

897 898 899 900
def test_forward_max():
    verify_max((1, 3, 20, 20))
    verify_max((20, 20))

901

902 903 904 905 906 907 908 909 910 911 912 913 914
def verify_mean(input_dim):
    dtype = 'float32'

    a_np1 = np.random.uniform(size=input_dim).astype(dtype)
    a_np2 = np.random.uniform(size=input_dim).astype(dtype)
    a_np3 = np.random.uniform(size=input_dim).astype(dtype)

    b_np = np.mean((a_np1, a_np2, a_np3), axis=0)

    mean_node = helper.make_node("Mean", ["a_np1", "a_np2", "a_np3"], ["out"])

    graph = helper.make_graph([mean_node],
                              "Mean_test",
915 916 917 918 919 920 921 922
                              inputs=[helper.make_tensor_value_info("a_np1",
                                                                    TensorProto.FLOAT, list(input_dim)),
                                      helper.make_tensor_value_info("a_np2",
                                                                    TensorProto.FLOAT, list(input_dim)),
                                      helper.make_tensor_value_info("a_np3",
                                                                    TensorProto.FLOAT, list(input_dim))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(b_np.shape))])
923 924 925 926

    model = helper.make_model(graph, producer_name='Mean_test')

    for target, ctx in ctx_list():
927 928
        tvm_out = get_tvm_output(
            model, [a_np1, a_np2, a_np3], target, ctx, b_np.shape)
929 930
        tvm.testing.assert_allclose(b_np, tvm_out, rtol=1e-5, atol=1e-5)

931

932 933 934 935
def test_forward_mean():
    verify_mean((1, 3, 20, 20))
    verify_mean((20, 20))

936

937 938 939 940 941 942 943
def verify_hardsigmoid(input_dim, alpha, beta):
    dtype = 'float32'

    a_np1 = np.random.uniform(size=input_dim).astype(dtype)

    b_np = np.clip(a_np1 * alpha + beta, 0, 1)

944 945
    hardsigmoid_node = helper.make_node("HardSigmoid", ["a_np1"], [
                                        "out"], alpha=alpha, beta=beta)
946 947 948

    graph = helper.make_graph([hardsigmoid_node],
                              "HardSigmoid_test",
949 950 951 952
                              inputs=[helper.make_tensor_value_info("a_np1",
                                                                    TensorProto.FLOAT, list(input_dim))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.FLOAT, list(b_np.shape))])
953 954 955 956 957 958 959

    model = helper.make_model(graph, producer_name='HardSigmoid_test')

    for target, ctx in ctx_list():
        tvm_out = get_tvm_output(model, [a_np1], target, ctx, b_np.shape)
        tvm.testing.assert_allclose(b_np, tvm_out, rtol=1e-5, atol=1e-5)

960

961 962 963 964
def test_forward_hardsigmoid():
    verify_hardsigmoid((1, 3, 20, 20), 0.5, 0.6)
    verify_hardsigmoid((20, 20), 0.3, 0.4)

965

966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
def verify_argmin(input_dim, axis=None, keepdims=None):
    def _argmin_numpy(data, axis=0, keepdims=True):
        result = np.argmin(data, axis=axis)
        if (keepdims == 1):
            result = np.expand_dims(result, axis)
        return result.astype(data.dtype)

    a_np1 = np.random.uniform(-10, 10, input_dim).astype(np.int32)
    if keepdims is None and axis is None:
        b_np = _argmin_numpy(a_np1)
        node = onnx.helper.make_node('ArgMin',
                                     inputs=['a_np1'],
                                     outputs=['out'])
    elif axis is None:
        b_np = _argmin_numpy(a_np1, keepdims=keepdims)
        node = onnx.helper.make_node('ArgMin',
                                     inputs=['a_np1'],
                                     outputs=['out'],
                                     keepdims=keepdims)
    elif keepdims is None:
        b_np = _argmin_numpy(a_np1, axis=axis)
        node = onnx.helper.make_node('ArgMin',
                                     inputs=['a_np1'],
                                     outputs=['out'],
                                     axis=axis)
    else:
        b_np = _argmin_numpy(a_np1, axis=axis, keepdims=keepdims)
        node = onnx.helper.make_node('ArgMin',
                                     inputs=['a_np1'],
                                     outputs=['out'],
                                     axis=axis,
                                     keepdims=keepdims)
    graph = helper.make_graph([node],
                              "argmin_test",
1000 1001 1002 1003
                              inputs=[helper.make_tensor_value_info("a_np1",
                                                                    TensorProto.INT32, list(a_np1.shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.INT32, list(b_np.shape))])
1004 1005 1006 1007

    model = helper.make_model(graph, producer_name='argmin_test')

    for target, ctx in ctx_list():
1008 1009
        tvm_out = get_tvm_output(
            model, [a_np1], target, ctx, b_np.shape, b_np.dtype)
1010 1011
        tvm.testing.assert_allclose(b_np, tvm_out, rtol=1e-5, atol=1e-5)

1012

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
def verify_argmax(input_dim, axis=None, keepdims=None):
    def _argmax_numpy(data, axis=0, keepdims=True):
        result = np.argmax(data, axis=axis)
        if (keepdims == 1):
            result = np.expand_dims(result, axis)
        return result.astype(data.dtype)

    a_np1 = np.random.uniform(-10, 10, input_dim).astype(np.int32)
    if keepdims is None and axis is None:
        b_np = _argmax_numpy(a_np1)
        node = onnx.helper.make_node('ArgMax',
                                     inputs=['a_np1'],
                                     outputs=['out'])
    elif axis is None:
        b_np = _argmax_numpy(a_np1, keepdims=keepdims)
        node = onnx.helper.make_node('ArgMax',
                                     inputs=['a_np1'],
                                     outputs=['out'],
                                     keepdims=keepdims)
    elif keepdims is None:
        b_np = _argmax_numpy(a_np1, axis=axis)
        node = onnx.helper.make_node('ArgMax',
                                     inputs=['a_np1'],
                                     outputs=['out'],
                                     axis=axis)
    else:
        b_np = _argmax_numpy(a_np1, axis=axis, keepdims=keepdims)
        node = onnx.helper.make_node('ArgMax',
                                     inputs=['a_np1'],
                                     outputs=['out'],
                                     axis=axis,
                                     keepdims=keepdims)

    graph = helper.make_graph([node],
                              "argmax_test",
1048 1049 1050 1051
                              inputs=[helper.make_tensor_value_info("a_np1",
                                                                    TensorProto.INT32, list(a_np1.shape))],
                              outputs=[helper.make_tensor_value_info("out",
                                                                     TensorProto.INT32, list(b_np.shape))])
1052 1053 1054 1055

    model = helper.make_model(graph, producer_name='argmax_test')

    for target, ctx in ctx_list():
1056 1057
        tvm_out = get_tvm_output(
            model, [a_np1], target, ctx, b_np.shape, b_np.dtype)
1058 1059
        tvm.testing.assert_allclose(b_np, tvm_out, rtol=1e-5, atol=1e-5)

1060

1061 1062
def test_forward_arg_min_max():
    '''Verify argmin and argmax'''
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    verify_argmin([3, 4, 4])
    verify_argmax([3, 4, 4])
    verify_argmin([3, 4, 4], axis=1)
    verify_argmax([3, 4, 4], axis=0)
    verify_argmin([3, 4, 4], keepdims=0)
    verify_argmax([3, 4, 4], keepdims=1)
    for axis in [None, 0, 1, 2]:
        for keepdims in [None, True, False]:
            verify_argmin([3, 4, 4], axis, keepdims)
            verify_argmax([3, 4, 4], axis, keepdims)


def verify_constantofshape(input_dim, value, dtype):
    out = np.empty(shape=input_dim, dtype=dtype)
1077 1078
    out.fill(value)

1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
    fill_node = helper.make_node("ConstantOfShape", ["input"], ["output"],
                                 value=helper.make_tensor(
                                     'value',
                                     mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)],
                                     (1, ), (value, )))

    inputs = [
        helper.make_tensor_value_info("input", TensorProto.FLOAT, input_dim)
    ]

    graph = helper.make_graph(
        [fill_node],
        "fill_test",
        inputs,
        outputs=[
            helper.make_tensor_value_info("output", TensorProto.FLOAT,
                                          list(out.shape))
        ],
        initializer=[
            helper.make_tensor("input", TensorProto.INT32, (len(input_dim), ),
                               input_dim)
        ])
1101 1102 1103 1104

    model = helper.make_model(graph, producer_name='fill_test')

    for target, ctx in ctx_list():
1105
        tvm_out = get_tvm_output(model, [], target, ctx, out.shape)
1106 1107 1108

        tvm.testing.assert_allclose(out, tvm_out, rtol=1e-5, atol=1e-5)

1109 1110 1111 1112 1113

def test_constantofshape():
    verify_constantofshape((2, 3, 4, 5), 10, 'float32')
    verify_constantofshape((3, 3), 0, 'int32')
    verify_constantofshape((1, 2, 3), -1, 'float32')
1114 1115


1116
def verify_pad(indata, pads, mode='constant', value=0.0):
1117 1118 1119 1120 1121
    indata = np.array(indata).astype(np.float32)
    #  numpy expect result
    len_dim = len(pads) // 2
    np_pads = [(pads[i], pads[i+len_dim]) for i in range(len_dim)]
    #  onnx graph
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
    if mode in ['edge', 'reflect']:
        outdata = np.pad(indata, pad_width=np_pads, mode=mode)
        node = helper.make_node(
            'Pad',
            inputs=['input'],
            outputs=['output'],
            mode=mode,
            pads=pads,
        )
    else:
1132 1133
        outdata = np.pad(indata, pad_width=np_pads,
                         mode='constant', constant_values=value)
1134 1135 1136 1137 1138 1139 1140 1141
        node = helper.make_node(
            'Pad',
            inputs=['input'],
            outputs=['output'],
            mode='constant',
            pads=pads,
            value=value
        )
1142 1143
    graph = helper.make_graph([node],
                              'pad_test',
1144 1145 1146 1147
                              inputs=[helper.make_tensor_value_info("input",
                                                                    TensorProto.FLOAT, list(indata.shape))],
                              outputs=[helper.make_tensor_value_info("output",
                                                                     TensorProto.FLOAT, list(outdata.shape))])
1148 1149 1150
    model = helper.make_model(graph, producer_name='pad_test')
    #  tvm result
    for target, ctx in ctx_list():
1151 1152
        tvm_out = get_tvm_output(
            model, indata, target, ctx, outdata.shape, 'float32')
1153 1154
    tvm.testing.assert_allclose(outdata, tvm_out, rtol=1e-5, atol=1e-5)

1155

1156
def test_pad():
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
    verify_pad(np.random.randn(2, 2).astype(
        np.float32), [0, 1, 0, 0], 'constant', 0.0)
    verify_pad(np.random.randn(2, 3).astype(
        np.float32), [1, 0, 0, 1], 'constant', 0.0)
    verify_pad(np.random.randn(3, 2).astype(
        np.float32), [0, 0, 1, 0], 'constant', 5.0)
    verify_pad(np.random.randn(1, 3, 4, 5).astype(
        np.float32), [0, 0, 1, 1, 0, 0, 1, 1], 'edge')
    verify_pad(np.random.randn(1, 3, 4, 5).astype(
        np.float32), [0, 0, 1, 1, 0, 0, 1, 1], 'reflect')

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192

def verify_reduce_x(name, indata, axis, keepdims):
    indata = np.array(indata).astype(np.float32)
    #  numpy expect result
    if name == 'ReduceMax':
        outdata = np.maximum.reduce(indata, axis=axis, keepdims=keepdims == 1)
    elif name == 'ReduceMin':
        outdata = np.minimum.reduce(indata, axis=axis, keepdims=keepdims == 1)
    elif name == 'ReduceSum':
        outdata = np.sum(indata, axis=axis, keepdims=keepdims == 1)
    elif name == 'ReduceMean':
        outdata = np.mean(indata, axis=axis, keepdims=keepdims == 1)
    else:
        raise Exception('unsupport op: {}'.format(name))
    if len(np.asarray(outdata).shape) == 0:
        outdata = np.asarray([outdata])
    #  onnx graph
    if axis is None:
        node = helper.make_node(name, inputs=['input'], outputs=['output'],
                                keepdims=keepdims)
    else:
        node = helper.make_node(name, inputs=['input'], outputs=['output'],
                                axes=axis, keepdims=keepdims)
    graph = helper.make_graph([node],
                              '{}_test'.format(name),
1193 1194 1195 1196
                              inputs=[helper.make_tensor_value_info("input",
                                                                    TensorProto.FLOAT, list(indata.shape))],
                              outputs=[helper.make_tensor_value_info("output",
                                                                     TensorProto.FLOAT, list(outdata.shape))])
1197 1198 1199
    model = helper.make_model(graph, producer_name='{}_test'.format(name))
    #  tvm result
    for target, ctx in ctx_list():
1200 1201
        tvm_out = get_tvm_output(
            model, indata, target, ctx, outdata.shape, 'float32')
1202 1203
    tvm.testing.assert_allclose(outdata, tvm_out, rtol=1e-5, atol=1e-5)

1204

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
def test_reduce_max():
    verify_reduce_x("ReduceMax",
                    np.random.randn(3, 2, 2).astype(np.float32),
                    axis=None, keepdims=1)
    verify_reduce_x("ReduceMax",
                    np.random.randn(3, 2, 3).astype(np.float32),
                    axis=None, keepdims=0)
    verify_reduce_x("ReduceMax",
                    np.random.randn(3, 3, 3).astype(np.float32),
                    axis=(1,), keepdims=1)

1216

1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
def test_reduce_min():
    verify_reduce_x("ReduceMin",
                    np.random.randn(3, 2, 2).astype(np.float32),
                    axis=None, keepdims=1)
    verify_reduce_x("ReduceMin",
                    np.random.randn(3, 2, 3).astype(np.float32),
                    axis=None, keepdims=0)
    verify_reduce_x("ReduceMin",
                    np.random.randn(3, 3, 3).astype(np.float32),
                    axis=(1,), keepdims=1)

1228

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
def test_reduce_sum():
    verify_reduce_x("ReduceSum",
                    np.random.randn(3, 2, 2).astype(np.float32),
                    axis=None, keepdims=1)
    verify_reduce_x("ReduceSum",
                    np.random.randn(3, 2, 3).astype(np.float32),
                    axis=None, keepdims=0)
    verify_reduce_x("ReduceSum",
                    np.random.randn(3, 3, 3).astype(np.float32),
                    axis=(1,), keepdims=1)

1240

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
def test_reduce_mean():
    verify_reduce_x("ReduceMean",
                    np.random.randn(3, 2, 2).astype(np.float32),
                    axis=None, keepdims=1)
    verify_reduce_x("ReduceMean",
                    np.random.randn(3, 2, 3).astype(np.float32),
                    axis=None, keepdims=0)
    verify_reduce_x("ReduceMean",
                    np.random.randn(3, 3, 3).astype(np.float32),
                    axis=(1,), keepdims=1)

1252

1253 1254 1255
def verify_split(indata, outdatas, split, axis=0):
    indata = np.array(indata).astype(np.float32)
    outdatas = [np.array(o).astype(np.float32) for o in outdatas]
1256 1257 1258 1259
    if split:
        split_index = range(len(split))
    else:
        split_index = range(len(outdatas))
1260 1261 1262
    node = helper.make_node(
        'Split',
        inputs=['input'],
1263
        outputs=['output_{}'.format(i) for i in range(len(split_index))],
1264 1265 1266 1267 1268
        axis=axis,
        split=split
    )
    graph = helper.make_graph([node],
                              'split_test',
1269 1270 1271 1272 1273 1274
                              inputs=[helper.make_tensor_value_info("input",
                                                                    TensorProto.FLOAT, list(indata.shape))],
                              outputs=[helper.make_tensor_value_info("output_{}".format(i),
                                                                     TensorProto.FLOAT, list(outdatas[i].shape))
                                       for i in range(len(split_index))
                                       ])
1275 1276 1277 1278 1279
    model = helper.make_model(graph, producer_name='split_test')

    for target, ctx in ctx_list():
        output_shape = [o.shape for o in outdatas]
        output_type = ['float32', 'float32', 'float32']
1280 1281
        tvm_out = get_tvm_output(
            model, indata, target, ctx, output_shape, output_type)
1282 1283 1284
    for o, t in zip(outdatas, tvm_out):
        tvm.testing.assert_allclose(o, t)

1285

1286 1287
def test_split():
    # 1D
1288 1289 1290 1291
    verify_split([1., 2., 3., 4., 5., 6.], [
                 [1., 2.], [3., 4.], [5., 6.]], [2, 2, 2], 0)
    verify_split([1., 2., 3., 4., 5., 6.], [
                 [1., 2.], [3.], [4., 5., 6.]], [2, 1, 3], 0)
1292 1293 1294
    # 2D
    verify_split([[1., 2., 3., 4.], [7., 8., 9., 10.]],
                 [[[1., 2.], [7., 8.]], [[3., 4.], [9., 10.]]], [2, 2], 1)
1295 1296 1297
    # Split evenly (unstack)
    verify_split([1, 2, 3], [[1], [2], [3]], False)

1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309

def test_binary_ops():
    in_shape = (1, 2, 3, 3)
    dtype = "float32"
    out_shape = in_shape

    def verify_binary_ops(op, x, y, out_np, broadcast=None):
        if broadcast is None:
            z = helper.make_node(op, ['in1', 'in2'], ['out'])
        else:
            z = helper.make_node(op, ['in1', 'in2'], ['out'], broadcast=1)
        graph = helper.make_graph([z],
1310 1311 1312 1313 1314 1315 1316
                                  '_test',
                                  inputs=[helper.make_tensor_value_info("in1",
                                                                        TensorProto.FLOAT, list(in_shape)),
                                          helper.make_tensor_value_info("in2",
                                                                        TensorProto.FLOAT, list(in_shape))],
                                  outputs=[helper.make_tensor_value_info("out",
                                                                         TensorProto.FLOAT, list(out_shape))])
1317 1318 1319 1320 1321 1322 1323 1324
        model = helper.make_model(graph, producer_name='_test')
        for target, ctx in ctx_list():
            tvm_out = get_tvm_output(model, [x, y], target, ctx)
            tvm.testing.assert_allclose(out_np, tvm_out, rtol=1e-5, atol=1e-5)

    x = np.random.uniform(size=in_shape).astype(dtype)
    y = np.random.uniform(size=in_shape).astype(dtype)
    z = np.random.uniform(size=(3,)).astype(dtype)
1325
    verify_binary_ops("Add", x, y, x + y, broadcast=None)
1326 1327 1328
    verify_binary_ops("Add", x, z,  x + z, broadcast=True)
    verify_binary_ops("Sub", x, y, x - y, broadcast=None)
    verify_binary_ops("Sub", x, z, x - z, broadcast=True)
1329
    verify_binary_ops("Mul", x, y, x * y, broadcast=None)
1330 1331 1332 1333
    verify_binary_ops("Mul", x, z,  x * z, broadcast=True)
    verify_binary_ops("Div", x, y, x / y, broadcast=None)
    verify_binary_ops("Div", x, z, x / z, broadcast=True)
    verify_binary_ops("Sum", x, y, x + y, broadcast=None)
1334 1335
    verify_binary_ops("Greater", x, y, x > y, broadcast=True)
    verify_binary_ops("Less", x, y, x < y, broadcast=True)
1336
    verify_binary_ops("Equal", x, y, x == y, broadcast=True)
1337

1338

1339 1340 1341 1342 1343 1344 1345 1346
def test_single_ops():
    in_shape = (1, 2, 3, 3)
    dtype = "float32"
    out_shape = in_shape

    def verify_single_ops(op, x, out_np, rtol=1e-5, atol=1e-5):
        z = helper.make_node(op, ['in1'], ['out'])
        graph = helper.make_graph([z],
1347 1348 1349 1350 1351
                                  '_test',
                                  inputs=[helper.make_tensor_value_info("in1",
                                                                        TensorProto.FLOAT, list(in_shape)), ],
                                  outputs=[helper.make_tensor_value_info("out",
                                                                         TensorProto.FLOAT, list(out_shape))])
1352 1353 1354 1355 1356 1357
        model = helper.make_model(graph, producer_name='_test')
        for target, ctx in ctx_list():
            tvm_out = get_tvm_output(model, [x], target, ctx)
            tvm.testing.assert_allclose(out_np, tvm_out, rtol=rtol, atol=atol)

    x = np.random.uniform(size=in_shape).astype(dtype)
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
    verify_single_ops("Neg", x, -x)
    verify_single_ops("Abs", x, np.abs(x))
    verify_single_ops("Reciprocal", x, 1/x)
    verify_single_ops("Sqrt", x, np.sqrt(x))
    verify_single_ops("Relu", x, np.maximum(x, 0))
    verify_single_ops("Exp", x, np.exp(x))
    verify_single_ops("Log", x, np.log(x))
    verify_single_ops("Log", x, np.log(x))
    verify_single_ops("Tanh", x, np.tanh(x))
    verify_single_ops("Sigmoid", x, 1 / (1 + np.exp(-x)))
    verify_single_ops("Softsign", x, x / (1 + np.abs(x)))
    verify_single_ops("SoftPlus", x, np.log(1 + np.exp(x)))

1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381

def test_leaky_relu():
    def leaky_relu_x(x, alpha):
        return np.where(x >= 0, x, x * alpha)
    _test_onnx_op_elementwise((2, 4, 5, 6),
                              leaky_relu_x,
                              {'alpha': 0.25},
                              'float32',
                              'LeakyRelu',
                              {'alpha': 0.25})

1382

1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
def test_elu():
    def elu_x(x, alpha):
        return np.where(x > 0, x, alpha * (np.exp(x) - 1.0))
    _test_onnx_op_elementwise((2, 4, 5, 6),
                              elu_x,
                              {'alpha': 0.25},
                              'float32',
                              'Elu',
                              {'alpha': 0.25})

1393

1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
def test_selu():
    def selu_x(x, alpha, gamma):
        return gamma * np.where(x > 0, x, alpha * (np.exp(x) - 1.0))
    _test_onnx_op_elementwise((2, 4, 5, 6),
                              selu_x,
                              {'alpha': 0.25, 'gamma': 0.3},
                              'float32',
                              'Selu',
                              {'alpha': 0.25, 'gamma': 0.3})

1404

1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
def test_ThresholdedRelu():
    def ThresholdedRelu_x(x, alpha):
        out_np = np.clip(x, alpha, np.inf)
        out_np[out_np == alpha] = 0
        return out_np
    _test_onnx_op_elementwise((2, 4, 5, 6),
                              ThresholdedRelu_x,
                              {'alpha': 0.25},
                              'float32',
                              'ThresholdedRelu',
                              {'alpha': 0.25})

1417

1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
def test_ScaledTanh():
    def ScaledTanh_x(x, alpha, beta):
        return alpha * np.tanh(beta * x)
    _test_onnx_op_elementwise((2, 4, 5, 6),
                              ScaledTanh_x,
                              {'alpha': 0.25, 'beta': 0.3},
                              'float32',
                              'ScaledTanh',
                              {'alpha': 0.25, 'beta': 0.3})

1428

1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
def test_ParametricSoftplus():
    def ParametricSoftplus_x(x, alpha, beta):
        return alpha * np.log(np.exp(beta * x) + 1)
    _test_onnx_op_elementwise((2, 4, 5, 6),
                              ParametricSoftplus_x,
                              {'alpha': 0.25, 'beta': 0.3},
                              'float32',
                              'ParametricSoftplus',
                              {'alpha': 0.25, 'beta': 0.3})

1439

1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
def test_Scale():
    def Scale_x(x, scale):
        return scale * x
    _test_onnx_op_elementwise((2, 4, 5, 6),
                              Scale_x,
                              {'scale': 0.25},
                              'float32',
                              'Scale',
                              {'scale': 0.25})

1450

1451 1452 1453 1454 1455 1456 1457 1458
def test_LogSoftmax():
    _test_onnx_op_elementwise((1, 4),
                              topi.testing.log_softmax_python,
                              {},
                              'float32',
                              'LogSoftmax',
                              {'axis': 1})

Zhi committed
1459 1460 1461 1462 1463

def check_torch_conversion(model, input_size):
    dummy_input = torch.randn(*input_size)
    file_name = '{}.onnx'.format(model.__name__)
    # Set verbose=True for more output
1464 1465
    torch.onnx.export(model(), dummy_input, file_name,
                      export_params=True, verbose=False)
Zhi committed
1466
    onnx_model = onnx.load(file_name)
1467 1468
    for target, ctx in ctx_list():
        input_data = np.random.uniform(size=input_size).astype('int32')
1469
        c2_out = get_onnxruntime_output(onnx_model, input_data)
1470 1471
        tvm_out = get_tvm_output(onnx_model, input_data, target, ctx)
        tvm.testing.assert_allclose(c2_out, tvm_out)
Zhi committed
1472

1473

Zhi committed
1474
def test_resnet():
1475
    check_torch_conversion(torchvision.models.resnet18, (1, 3, 224, 224))
Zhi committed
1476 1477 1478
    # check_torch_conversion(torchvision.models.resnet101, (1,3,224,224))

# def test_alexnet():
1479 1480
# Torch's ONNX export does not support the adaptive pooling used by AlexNet?
# check_torch_conversion(torchvision.models.alexnet, (1,3,224,224))
Zhi committed
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490

# Torch's ONNX export does not support the adaptive pooling used by vgg16?
# def test_vgg16():
#     check_torch_conversion(torchvision.models.vgg16, (1,3,224,224))

# TODO(@jroesch): Update Torch + ONNX to support this import.
# def test_squeezenet():
#     # Torch's ONNX export does not support the max pooling used by Squezenet
#     check_torch_conversion(torchvision.models.squeezenet1_0, (1,3,224,224))

1491

Zhi committed
1492
def test_densenet():
1493 1494
    check_torch_conversion(torchvision.models.densenet161, (1, 3, 224, 224))

Zhi committed
1495 1496

def test_inception():
1497
    check_torch_conversion(torchvision.models.inception_v3, (1, 3, 224, 224))
Zhi committed
1498 1499 1500 1501 1502 1503 1504 1505 1506

# TODO(@jroesch): Update Torch + ONNX to support this import.
# def test_googlenet():
#     check_torch_conversion(torchvision.models.googlenet, (1,3,224,224))

# TODO(@jroesch): Update Torch + ONNX to support this import.
# def test_shufflenetv2():
#     check_torch_conversion(torchvision.models.shufflenetv2, (1,3,224,224))

1507

1508 1509 1510 1511 1512 1513 1514 1515 1516
def test_sign():
    def Sign_x(x):
        return np.sign(x)
    _test_onnx_op_elementwise((3, 4, 5, 6),
                              Sign_x,
                              {},
                              'float32',
                              'Sign',
                              {})
Zhi committed
1517

1518 1519 1520 1521 1522 1523 1524 1525 1526

def verify_not(indata, dtype):
    x = indata.astype(dtype)
    outdata = np.logical_not(x)

    node = helper.make_node('Not', inputs=['in'], outputs=['out'],)

    graph = helper.make_graph([node],
                              'not_test',
1527 1528
                              inputs=[helper.make_tensor_value_info(
                                  "in", TensorProto.BOOL, list(x.shape))],
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
                              outputs=[helper.make_tensor_value_info("out", TensorProto.BOOL, list(outdata.shape))])

    model = helper.make_model(graph, producer_name='not_test')

    for target, ctx in ctx_list():
        tvm_out = get_tvm_output(model, [x], target, ctx, outdata.shape)
        tvm.testing.assert_allclose(outdata, tvm_out)


def test_not():
    # 2d
    verify_not(indata=(np.random.randn(3, 4) > 0), dtype=bool)
    # 3d
    verify_not(indata=(np.random.randn(3, 4, 5) > 0), dtype=bool)
    # 4d
    verify_not(indata=(np.random.randn(3, 4, 5, 6) > 0), dtype=bool)


1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
def verify_and(indata, dtype):
    x = indata[0].astype(dtype)
    y = indata[1].astype(dtype)
    outdata = np.logical_and(x, y)

    node = helper.make_node('And', inputs=['in1', 'in2'], outputs=['out'], )

    graph = helper.make_graph([node],
                              'and_test',
                              inputs=[helper.make_tensor_value_info("in1", TensorProto.BOOL, list(x.shape)),
                                      helper.make_tensor_value_info("in2", TensorProto.BOOL, list(y.shape))],
                              outputs=[helper.make_tensor_value_info("out", TensorProto.BOOL, list(outdata.shape))])

    model = helper.make_model(graph, producer_name='and_test')

    for target, ctx in ctx_list():
        tvm_out = get_tvm_output(model, [x, y], target, ctx, outdata.shape)
        tvm.testing.assert_allclose(outdata, tvm_out)


def test_and():
    # 2d
    x = (np.random.randn(3, 4) > 0)
    y = (np.random.randn(3, 4) > 0)
    verify_and(indata=[x, y], dtype=bool)

    # 3d
    x = (np.random.randn(3, 4, 5) > 0)
    y = (np.random.randn(3, 4, 5) > 0)
    verify_and(indata=[x, y], dtype=bool)

    # 4d
    x = (np.random.randn(3, 4, 5, 6) > 0)
    y = (np.random.randn(3, 4, 5, 6) > 0)
    verify_and(indata=[x, y], dtype=bool)

    # 3d vs 1d
    x = (np.random.randn(3, 4, 5) > 0)
    y = (np.random.randn(5) > 0)
    verify_and(indata=[x, y], dtype=bool)

    # 3d vs 2d
    x = (np.random.randn(3, 4, 5) > 0)
    y = (np.random.randn(4, 5) > 0)
    verify_and(indata=[x, y], dtype=bool)


1594
def verify_tile_v1(indata, outdata, **kwargs):
1595 1596 1597
    node = helper.make_node('Tile', inputs=['in'], outputs=['out'], **kwargs)
    graph = helper.make_graph([node],
                              'tile_test',
1598 1599
                              inputs=[helper.make_tensor_value_info(
                                  "in", TensorProto.FLOAT, list(indata.shape))],
1600 1601 1602 1603 1604
                              outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(outdata.shape))])

    model = helper.make_model(graph, producer_name='tile_test')

    for target, ctx in ctx_list():
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
        tvm_out = get_tvm_output(
            model, [indata], target, ctx, outdata.shape, opset=1)
        tvm.testing.assert_allclose(outdata, tvm_out)


def verify_tile_v6(indata, repeats, outdata):
    node = helper.make_node('Tile',
                            inputs=['input', 'repeats'],
                            outputs=['out'])
    graph = helper.make_graph(
        [node],
        'tile_test',
        inputs=[
            helper.make_tensor_value_info("input", TensorProto.FLOAT,
                                          list(indata.shape)),
            helper.make_tensor_value_info("repeats", TensorProto.INT64,
                                          list(repeats.shape))
        ],
        outputs=[
            helper.make_tensor_value_info("out", TensorProto.FLOAT,
                                          list(outdata.shape))
        ],
        initializer=[
            helper.make_tensor("repeats", TensorProto.INT64,
                               list(repeats.shape), repeats)
        ])

    model = helper.make_model(graph, producer_name='tile_test')

    for target, ctx in ctx_list():
        tvm_out = get_tvm_output(model, [indata],
                                 target,
                                 ctx,
                                 outdata.shape,
                                 opset=6)
1640 1641 1642 1643 1644
        tvm.testing.assert_allclose(outdata, tvm_out)


def test_tile():
    x = np.random.rand(2, 3, 4, 5).astype(np.float32)
1645 1646
    repeats = np.random.randint(
        low=1, high=10, size=(np.ndim(x),)).astype(np.int64)
1647
    z = np.tile(x, repeats)
1648 1649 1650
    verify_tile_v1(x, z, repeats=repeats)
    verify_tile_v6(x, repeats, z)

1651

1652 1653 1654 1655
def verify_erf(indata, outdata):
    node = helper.make_node('Erf', inputs=['in'], outputs=['out'])
    graph = helper.make_graph([node],
                              'erf_test',
1656 1657
                              inputs=[helper.make_tensor_value_info(
                                  'in', TensorProto.FLOAT, list(indata.shape))],
1658 1659 1660 1661 1662 1663 1664
                              outputs=[helper.make_tensor_value_info('out', TensorProto.FLOAT, list(outdata.shape))])
    model = helper.make_model(graph, producer_name='erf_test')

    for target, ctx in ctx_list():
        tvm_out = get_tvm_output(model, [indata], target, ctx, outdata.shape)
        tvm.testing.assert_allclose(outdata, tvm_out)

1665

1666 1667 1668 1669 1670
def test_erf():
    x = np.random.rand(2, 3, 4, 6).astype(np.float32)
    z = scipy.special.erf(x)
    verify_erf(x, z)

1671

1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
def verify_where(condition, x, y, dtype, outdata):
    node = helper.make_node('Where', inputs=['condition', 'x', 'y'], outputs=['out'])
    graph = helper.make_graph([node],
                              'where_test',
                              inputs=[helper.make_tensor_value_info('condition', TensorProto.BOOL, list(condition.shape)),
                                      helper.make_tensor_value_info('x', dtype, list(x.shape)),
                                      helper.make_tensor_value_info('y', dtype, list(y.shape))],
                              outputs=[helper.make_tensor_value_info('out', dtype, list(outdata.shape))])
    model = helper.make_model(graph, producer_name='where_test')

    for target, ctx in ctx_list():
        tvm_out = get_tvm_output(model, [condition, x, y], target, ctx, outdata.shape)
        tvm.testing.assert_allclose(outdata, tvm_out)

1686

1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
def test_where():
    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)
    outdata = np.where(condition, x, y)
    verify_where(condition, x, y, TensorProto.INT64, outdata)

    x = np.array([[1, 2], [3, 4]], dtype=np.float32)
    y = np.array([[9, 8], [7, 6]], dtype=np.float32)
    outdata = np.where(condition, x, y)
    verify_where(condition, x, y, TensorProto.FLOAT, outdata)

1699 1700 1701 1702 1703
    x = np.array(1, dtype=np.float32)
    y = np.array([2], dtype=np.float32)
    outdata = np.where(condition, x, y)
    verify_where(condition, x, y, TensorProto.FLOAT, outdata)

1704

1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
def verify_or(indata, dtype):
    x = indata[0].astype(dtype)
    y = indata[1].astype(dtype)
    outdata = np.logical_or(x, y)

    node = helper.make_node('Or', inputs=['in1', 'in2'], outputs=['out'], )

    graph = helper.make_graph([node],
                              'or_test',
                              inputs=[helper.make_tensor_value_info("in1", TensorProto.BOOL, list(x.shape)),
                                      helper.make_tensor_value_info("in2", TensorProto.BOOL, list(y.shape))],
                              outputs=[helper.make_tensor_value_info("out", TensorProto.BOOL, list(outdata.shape))])

    model = helper.make_model(graph, producer_name='or_test')

    for target, ctx in ctx_list():
        tvm_out = get_tvm_output(model, [x, y], target, ctx, outdata.shape)
        tvm.testing.assert_allclose(outdata, tvm_out)


def test_or():
    # 2d
    x = (np.random.randn(3, 4) > 0)
    y = (np.random.randn(3, 4) > 0)
    verify_or(indata=[x, y], dtype=bool)

    # 3d
    x = (np.random.randn(3, 4, 5) > 0)
    y = (np.random.randn(3, 4, 5) > 0)
    verify_or(indata=[x, y], dtype=bool)

    # 4d
    x = (np.random.randn(3, 4, 5, 6) > 0)
    y = (np.random.randn(3, 4, 5, 6) > 0)
    verify_or(indata=[x, y], dtype=bool)

    # 3d vs 1d
    x = (np.random.randn(3, 4, 5) > 0)
    y = (np.random.randn(5) > 0)
    verify_or(indata=[x, y], dtype=bool)

    # 3d vs 2d
    x = (np.random.randn(3, 4, 5) > 0)
    y = (np.random.randn(4, 5) > 0)
    verify_or(indata=[x, y], dtype=bool)


1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
def verify_conv(x_shape, w_shape, y_shape, p):
    node = 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=p,)

    graph = helper.make_graph([node],
                              'conv_test',
                              inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(x_shape)),
                                      helper.make_tensor_value_info("W", TensorProto.FLOAT, list(w_shape))],
                              outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(y_shape))])

    model = helper.make_model(graph, producer_name='conv_test')

    for target, ctx in ctx_list():
        x = np.random.uniform(size=x_shape).astype('float32')
        W = np.random.uniform(size=w_shape).astype('float32')
        tvm_out = get_tvm_output(model, [x, W], target, ctx, y_shape)
        onnx_out = get_onnxruntime_output(model, [x, W], 'float32')[0]
        tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-5, atol=1e-5)


def test_conv():
    # Convolution with padding
    # (1, 1, 5, 5) input tensor
    # (1, 1, 3, 3) tensor for convolution weights
    # (1, 1, 5, 5) output tensor
    # [1, 1, 1, 1] list for pads
    verify_conv((1, 1, 5, 5), (1, 1, 3, 3), (1, 1, 5, 5), [1, 1, 1, 1])

    # Convolution without padding
    # (1, 1, 5, 5) input tensor
    # (1, 1, 3, 3) tensor for convolution weights
    # (1, 1, 3, 3) output tensor
    # [0, 0, 0, 0] list for pads
    verify_conv((1, 1, 5, 5), (1, 1, 3, 3), (1, 1, 3, 3), [0, 0, 0, 0])


def verify_convtranspose(x_shape, w_shape, y_shape, p):
    node = onnx.helper.make_node("ConvTranspose",
                                 inputs=["x", "W"],
                                 outputs=['y'],
                                 strides=[3, 2],
                                 group=1,
                                 kernel_shape=[3, 3],
                                 pads=p)

    graph = helper.make_graph([node],
                              'verify_convtranspose_test',
                              inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(x_shape)),
                                      helper.make_tensor_value_info("W", TensorProto.FLOAT, list(w_shape))],
                              outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(y_shape))])

    model = helper.make_model(graph, producer_name='convtranspose_trest')

    for target, ctx in ctx_list():
        x = np.random.uniform(size=x_shape).astype('float32')
        W = np.random.uniform(size=w_shape).astype('float32')
        tvm_out = get_tvm_output(model, [x, W], target, ctx, y_shape)
        onnx_out = get_onnxruntime_output(model, [x, W], 'float32')[0]
        tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-5, atol=1e-5)


def test_convtranspose():
    # Convolution Transpose with padding
    # (1, 1, 3, 3) input tensor
    # (1, 2, 3, 3) tensor for convolution weights
    # (1, 2, 7, 3) output tensor
    # [1, 2, 1, 2] list for pads
    verify_convtranspose((1, 1, 3, 3), (1, 2, 3, 3), (1, 2, 7, 3), [1, 2, 1, 2])


1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
def test_unsqueeze_constant():
    from torch.nn import Linear, Sequential, Module
    class Flatten(Module):
        def forward(self, input):
            return input.view(input.size(0), -1)

    import tempfile
    with tempfile.NamedTemporaryFile() as fp:
        file_name = fp.name
        input_size = (1, 16, 32, 32)
        dummy_input = torch.randn(*input_size)
        layer = Sequential(Flatten(), Linear(16 * 32 * 32, 64))
        torch.onnx.export(layer, dummy_input, file_name, export_params=True)

        onnx_model = onnx.load(file_name)
        relay.frontend.from_onnx(onnx_model, {'0': input_size})


1847
if __name__ == '__main__':
1848
    test_flatten()
1849
    test_reshape()
1850
    test_shape()
1851
    test_expand()
1852 1853 1854 1855 1856 1857 1858
    test_power()
    test_squeeze()
    test_unsqueeze()
    test_slice()
    test_floor()
    test_ceil()
    test_clip()
1859
    test_onehot()
1860
    test_matmul()
1861
    test_batch_matmul()
1862 1863
    test_gather()
    test_lrn()
1864
    test_instance_norm()
1865 1866 1867 1868 1869 1870 1871
    test_upsample()
    test_forward_min()
    test_forward_max()
    test_forward_mean()
    test_forward_hardsigmoid()
    test_forward_arg_min_max()
    test_softmax()
1872
    test_constantofshape()
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
    test_reduce_max()
    test_reduce_min()
    test_reduce_sum()
    test_reduce_mean()
    test_pad()
    test_split()
    test_binary_ops()
    test_single_ops()
    test_leaky_relu()
    test_elu()
    test_selu()
    test_ThresholdedRelu()
    test_ScaledTanh()
    test_ParametricSoftplus()
    test_Scale()
    test_LogSoftmax()
Zhi committed
1889 1890 1891
    test_resnet()
    test_inception()
    test_densenet()
1892
    test_sign()
1893
    test_not()
1894
    test_and()
1895
    test_tile()
1896
    test_erf()
1897
    test_where()
1898
    test_or()
1899 1900
    test_depth_to_space()
    test_space_to_depth()
1901 1902
    test_conv()
    test_convtranspose()
1903
    test_unsqueeze_constant()