test_forward.py 109 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 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
# pylint: disable=import-self, invalid-name, unused-argument
"""
Tensorflow testcases
====================
This article is a test script to test tensorflow operator with Relay.
"""
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import graph_util
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.ops import init_ops
35
from distutils.version import LooseVersion
36 37
import tvm
from tvm import relay
38 39 40 41 42
import tvm.relay.testing.tf as tf_testing

#######################################################################
# Generic run functions for TVM & tensorflow
# ------------------------------------------
43 44


45 46 47 48 49
def convert_to_list(x):
    if not isinstance(x, list):
        x = [x]
    return x

50 51 52 53 54 55 56 57 58 59 60
tf_dtypes = {
    'float32': tf.float32,
    'float16': tf.float16,
    'float64': tf.float64,
    'int32': tf.int32,
    'uint8' : tf.uint8,
    'int8': tf.int8,
    'int16': tf.int16,
    'uint16': tf.uint16,
    'int64': tf.int64,
}
61

Wei Chen committed
62
def vmobj_to_list(o):
63
    if isinstance(o, tvm.relay.backend.vmobj.Tensor):
Wei Chen committed
64
        return [o.asnumpy().tolist()]
65
    elif isinstance(o, tvm.relay.backend.vmobj.ADT):
Wei Chen committed
66 67 68 69 70 71 72 73 74 75
        result = []
        for f in o:
            result.extend(vmobj_to_list(f))
        return result
    elif isinstance(o, tvm.relay.backend.interpreter.TupleValue):
        result = []
        for f in o.fields:
            result.append(vmobj_to_list(f))
        return result
    elif isinstance(o, tvm.relay.backend.interpreter.ConstructorValue):
76
        if o.constructor.name_hint == 'Cons':
Wei Chen committed
77 78 79 80
            tl = vmobj_to_list(o.fields[1])
            hd = vmobj_to_list(o.fields[0])
            hd.extend(tl)
            return hd
81
        elif o.constructor.name_hint == 'Nil':
Wei Chen committed
82
            return []
83 84 85 86 87
        elif 'tensor_nil' in o.constructor.name_hint:
            return [0]
        elif 'tensor' in o.constructor.name_hint:
            return [o.fields[0].asnumpy()]
        else:
88 89
            raise RuntimeError("Unknown object type: %s" %
                               o.constructor.name_hint)
Wei Chen committed
90 91 92 93 94
    elif isinstance(o, tvm.relay.backend.interpreter.TensorValue):
        return [o.data.asnumpy()]
    else:
        raise RuntimeError("Unknown object type: %s" % type(o))

95

96
def run_tvm_graph(graph_def, input_data, input_node, num_output=1,
Wei Chen committed
97
                  target='llvm', out_names=None, opt_level=3, mode='graph_runtime'):
98 99 100 101 102 103
    """ Generic function to compile on relay and execute on tvm """
    input_data = convert_to_list(input_data)
    input_node = convert_to_list(input_node)
    layout = None
    if target == "cuda":
        layout = "NCHW"
104 105
    target_host = None
    shape_dict = {e: i.shape for e, i in zip(input_node, input_data)}
106
    mod, params = relay.frontend.from_tensorflow(graph_def,
107 108 109
                                                 layout=layout,
                                                 shape=shape_dict,
                                                 outputs=out_names)
Wei Chen committed
110 111 112 113
    if mode in ['debug', 'vm']:
        ex = relay.create_executor(mode, mod=mod, ctx=tvm.cpu(), target="llvm")
        inputs = []
        for param in mod['main'].params:
114 115 116 117 118 119 120 121 122
            found = False
            for i, n in enumerate(input_node):
                if n == param.name_hint:
                    found = True
                    inputs.append(tvm.nd.array(input_data[i]))
                    break
            # Interpreter doesn't bind constants, so still need to find in params
            if not found:
                inputs.append(tvm.nd.array(params[param.name_hint]))
Wei Chen committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
        result = ex.evaluate()(*inputs)
        return vmobj_to_list(result)
    else:
        with relay.build_config(opt_level=opt_level):
            graph, lib, params = relay.build(mod, target, target_host, params)

        ctx = tvm.context(target, 0)
        from tvm.contrib import graph_runtime
        m = graph_runtime.create(graph, lib, ctx)
        # set inputs
        for e, i in zip(input_node, input_data):
            m.set_input(e, tvm.nd.array(i))

        m.set_input(**params)
        # execute
        m.run()
        # get outputs
        assert out_names is None or num_output == len(out_names), (
            "out_names: {} num_output: {}".format(out_names, num_output))
142 143
        tvm_output_list = [m.get_output(i).asnumpy()
                           for i in range(num_output)]
Wei Chen committed
144
        return tvm_output_list
145

146

147 148 149 150 151 152
def run_tf_graph(sess, input_data, input_node, output_node):
    """ Generic function to execute tensorflow """
    input_data = convert_to_list(input_data)
    input_node = convert_to_list(input_node)
    output_node = convert_to_list(output_node)

153 154
    tensor = [sess.graph.get_tensor_by_name(
        output_name) for output_name in output_node]
155

156
    input_dict = {e: input_data[i] for i, e in enumerate(input_node)}
157 158 159 160 161

    output_data = sess.run(tensor, input_dict)
    return output_data


162
def compare_tf_with_tvm(in_data, in_name, out_name, init_global_variables=False,
Wei Chen committed
163
                        no_gpu=False, opt_level=3, mode='graph_runtime'):
164
    """Generic function to generate and compare tensorflow and TVM output"""
165 166
    def name_without_num(name):
        return name.split(':')[0] if ":" in name else name
167 168

    out_name = convert_to_list(out_name)
169
    out_node = [name_without_num(name) for name in out_name]
170 171 172

    in_data = convert_to_list(in_data)
    in_name = convert_to_list(in_name)
173
    in_node = [name_without_num(name) for name in in_name]
174 175 176 177 178 179 180
    with tf.Session() as sess:
        if init_global_variables:
            sess.run(variables.global_variables_initializer())
        final_graph_def = tf.graph_util.convert_variables_to_constants(
            sess,
            sess.graph.as_graph_def(add_shapes=True),
            out_node,
181
        )
182 183 184 185 186 187 188 189 190 191
        tf_output = run_tf_graph(sess, in_data, in_name, out_name)

        for device in ["llvm", "cuda"]:
            ctx = tvm.context(device, 0)
            if not ctx.exist:
                print("Skip because %s is not enabled" % device)
                continue
            if no_gpu and device == 'cuda':
                continue

192 193
            tvm_output = run_tvm_graph(final_graph_def, in_data, in_node,
                                       target=device, out_names=out_name,
Wei Chen committed
194
                                       num_output=len(out_name), opt_level=opt_level, mode=mode)
195 196 197
            # since the names from tensorflow and relay runs are not exactly same,
            # first len(tf_output) will be compared
            for i in range(len(tf_output)):
198 199
                tvm.testing.assert_allclose(
                    tf_output[i], tvm_output[i], atol=1e-5, rtol=1e-5)
200 201 202

        sess.close()

203

204 205 206 207 208 209 210 211 212 213 214 215 216
def is_gpu_available():
    from tensorflow.python.client import device_lib
    local_device_protos = device_lib.list_local_devices()
    gpu_list = [x.name for x in local_device_protos if x.device_type == 'GPU']
    if len(gpu_list) > 0:
        print("Tensorflow GPU:", gpu_list)
        return True
    else:
        return False

#######################################################################
# Pooling
# -------
217 218


219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
def _test_pooling_iteration(input_shape, **kwargs):
    """ One iteration of pool operation with given shapes and attributes """

    x = -np.arange(
        np.prod(input_shape), dtype=np.float32).reshape(input_shape) - 1

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=input_shape, dtype='float32')
        nn_ops.pool(in_data, **kwargs)

        if kwargs['pooling_type'] == 'MAX':
            out_name = 'max_pool:0'
        else:
            out_name = 'avg_pool:0'

        compare_tf_with_tvm(x, 'Placeholder:0', out_name)

236

237 238 239
def _test_pooling(input_shape, **kwargs):
    _test_pooling_iteration(input_shape, **kwargs)

240
    if is_gpu_available() and (len(input_shape) == 4):
241
        input_shape = [input_shape[ii] for ii in (0, 3, 1, 2)]
242
        kwargs['data_format'] = 'NCHW'
243 244
        _test_pooling_iteration(input_shape, **kwargs)

245

246 247 248 249
def test_forward_pooling():
    """ Pooling """

    for pool_type in ['AVG', 'MAX']:
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        _test_pooling(input_shape=[2, 9, 10, 2],
                      window_shape=[1, 1],
                      padding='SAME',
                      pooling_type=pool_type,
                      dilation_rate=[1, 1],
                      strides=[1, 1])

        _test_pooling(input_shape=[2, 10, 9, 2],
                      window_shape=[1, 1],
                      padding='SAME',
                      pooling_type=pool_type,
                      dilation_rate=[1, 1],
                      strides=[1, 1])

        _test_pooling(input_shape=[2, 9, 10, 2],
                      window_shape=[2, 1],
                      padding='SAME',
                      pooling_type=pool_type,
                      dilation_rate=[1, 1],
                      strides=[1, 1])

        _test_pooling(input_shape=[2, 10, 9, 2],
                      window_shape=[2, 3],
                      padding='SAME',
                      pooling_type=pool_type,
                      dilation_rate=[1, 1],
                      strides=[2, 1])

        # Tests involving SpaceToBatchND
        _test_pooling(input_shape=[1, 1, 2, 1],
                      window_shape=[1, 1],
                      padding='VALID',
                      pooling_type=pool_type,
                      dilation_rate=[1, 2])

        _test_pooling(input_shape=[1, 2, 1],
                      window_shape=[1],
                      padding='VALID',
                      pooling_type=pool_type,
                      dilation_rate=[2])
290

291 292 293 294
#######################################################################
# Convolution
# -----------

295

296
def _test_convolution(opname, tensor_in_sizes, filter_in_sizes,
297 298
                      dilations, strides, padding, data_format,
                      deconv_output_shape=[]):
299 300
    """ One iteration of convolution with given shapes and attributes """

301 302
    total_size_1 = np.prod(tensor_in_sizes)
    total_size_2 = np.prod(filter_in_sizes)
303 304 305 306 307 308 309
    # Initializes the input tensor with array containing incrementing
    # numbers from 1.
    data_array = [f * 1.0 for f in range(1, total_size_1 + 1)]
    filter_array = [f * 1.0 for f in range(1, total_size_2 + 1)]

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype='float32')
310 311
        in_filter = constant_op.constant(
            filter_array, shape=filter_in_sizes, dtype='float32')
312 313 314 315 316 317
        if data_format == 'NHWC':
            strides = [1] + strides + [1]
            dilations = [1] + dilations + [1]
        else:
            strides = [1, 1] + strides
            dilations = [1, 1] + dilations
318

319 320 321 322 323 324 325
        if opname == 'conv':
            nn_ops.conv2d(in_data,
                          in_filter,
                          strides=strides,
                          dilations=dilations,
                          padding=padding,
                          data_format=data_format)
326

327 328
            compare_tf_with_tvm(np.reshape(data_array, tensor_in_sizes).astype('float32'),
                                'Placeholder:0', 'Conv2D:0')
329 330 331 332 333 334 335 336 337 338
        elif opname == 'conv_transpose':
            nn_ops.conv2d_transpose(in_data,
                                    in_filter,
                                    output_shape=deconv_output_shape,
                                    strides=strides,
                                    padding=padding,
                                    data_format=data_format)

            compare_tf_with_tvm(np.reshape(data_array, tensor_in_sizes).astype('float32'),
                                'Placeholder:0', 'conv2d_transpose:0')
339 340
        else:
            nn_ops.depthwise_conv2d_native(in_data,
341 342 343 344 345
                                           in_filter,
                                           strides=strides,
                                           dilations=dilations,
                                           padding=padding,
                                           data_format=data_format)
346 347 348

            compare_tf_with_tvm(np.reshape(data_array, tensor_in_sizes).astype('float32'),
                                'Placeholder:0', 'DepthwiseConv2dNative:0')
349

350

351 352
def test_forward_convolution():
    if is_gpu_available():
353 354 355 356 357 358 359 360
        _test_convolution('conv', [4, 176, 8, 8], [1, 1, 176, 32], [1, 1], [1, 1], 'SAME', 'NCHW')
        _test_convolution('conv', [4, 19, 17, 17], [3, 3, 19, 19], [1, 1], [2, 2], 'VALID', 'NCHW')
        _test_convolution('conv', [4, 124, 17, 17], [1, 1, 124, 19], [1, 1], [1, 1], 'SAME', 'NCHW')
        _test_convolution('conv', [4, 12, 17, 17], [3, 3, 12, 32], [1, 1], [2, 2], 'VALID', 'NCHW')
        _test_convolution('depthwise', [4, 176, 8, 8], [1, 1, 176, 1], [1, 1], [1, 1], 'SAME', 'NCHW')
        _test_convolution('depthwise', [4, 19, 17, 17], [3, 3, 19, 1], [1, 1], [2, 2], 'VALID', 'NCHW')
        _test_convolution('depthwise', [4, 124, 17, 17], [1, 1, 124, 1], [1, 1], [1, 1], 'SAME', 'NCHW')
        _test_convolution('depthwise', [4, 12, 17, 17], [3, 3, 12, 1], [1, 1], [2, 2], 'VALID', 'NCHW')
361
        _test_convolution('depthwise', [4, 12, 17, 17], [3, 3, 12, 2], [1, 1], [2, 2], 'VALID', 'NCHW')
362 363 364 365 366 367 368 369
        _test_convolution('conv_transpose', [4, 32, 8, 8], [1, 1, 176, 32], [1, 1], [1, 1], 'SAME',
                          'NCHW', [4, 176, 8, 8])
        _test_convolution('conv_transpose', [4, 19, 8, 8], [3, 3, 19, 19], [1, 1], [2, 2], 'VALID',
                          'NCHW', [4, 19, 17, 17])
        _test_convolution('conv_transpose', [4, 19, 17, 17], [1, 1, 124, 19], [1, 1], [1, 1], 'SAME',
                          'NCHW', [4, 124, 17, 17])
        _test_convolution('conv_transpose', [4, 32, 8, 8], [3, 3, 12, 32], [1, 1], [2, 2], 'VALID',
                          'NCHW', [4, 12, 17, 17])
370 371 372 373 374 375 376 377
        # kernel 2x2, strides (2,2)
        _test_convolution('conv_transpose', [4, 19, 8, 8], [2, 2, 19, 19], [1, 1], [2, 2], 'VALID',
                          'NCHW', [4, 19, 16, 16])
        _test_convolution('conv_transpose', [4, 32, 8, 8], [2, 2, 12, 32], [1, 1], [2, 2], 'VALID',
                          'NCHW', [4, 12, 16, 16])
        # output channel is 1
        _test_convolution('conv_transpose', [1, 19, 8, 8], [1, 1, 1, 19], [1, 1], [1, 1], 'VALID',
                          'NCHW', [1, 1, 8, 8])
378 379 380 381 382 383 384 385 386

    _test_convolution('conv', [4, 8, 8, 176], [1, 1, 176, 32], [1, 1], [1, 1], 'SAME', 'NHWC')
    _test_convolution('conv', [4, 17, 17, 19], [3, 3, 19, 19], [1, 1], [2, 2], 'VALID', 'NHWC')
    _test_convolution('conv', [4, 17, 17, 124], [1, 1, 124, 19], [1, 1], [1, 1], 'SAME', 'NHWC')
    _test_convolution('conv', [4, 17, 17, 12], [3, 3, 12, 32], [1, 1], [2, 2], 'VALID', 'NHWC')
    _test_convolution('depthwise', [4, 8, 8, 176], [1, 1, 176, 1], [1, 1], [1, 1], 'SAME', 'NHWC')
    _test_convolution('depthwise', [4, 17, 17, 19], [3, 3, 19, 1], [1, 1], [2, 2], 'VALID', 'NHWC')
    _test_convolution('depthwise', [4, 17, 17, 124], [1, 1, 124, 1], [1, 1], [1, 1], 'SAME', 'NHWC')
    _test_convolution('depthwise', [4, 17, 17, 12], [3, 3, 12, 1], [1, 1], [2, 2], 'VALID', 'NHWC')
387
    _test_convolution('depthwise', [4, 17, 17, 12], [3, 3, 12, 2], [1, 1], [2, 2], 'VALID', 'NHWC')
388 389 390 391 392 393 394 395
    _test_convolution('conv_transpose', [4, 8, 8, 32], [1, 1, 176, 32], [1, 1], [1, 1], 'SAME',
                      'NHWC', [4, 8, 8, 176])
    _test_convolution('conv_transpose', [4, 8, 8, 19], [3, 3, 19, 19], [1, 1], [2, 2], 'VALID',
                      'NHWC', [4, 17, 17, 19])
    _test_convolution('conv_transpose', [4, 17, 17, 19], [1, 1, 124, 19], [1, 1], [1, 1], 'SAME',
                      'NHWC', [4, 17, 17, 124])
    _test_convolution('conv_transpose', [4, 8, 8, 32], [3, 3, 12, 32], [1, 1], [2, 2], 'VALID',
                      'NHWC', [4, 17, 17, 12])
396 397 398 399 400 401 402 403
    # kernel 2x2, strides (2,2)
    _test_convolution('conv_transpose', [4, 8, 8, 19], [2, 2, 19, 19], [1, 1], [2, 2], 'VALID',
                      'NHWC', [4, 16, 16, 19])
    _test_convolution('conv_transpose', [4, 8, 8, 32], [2, 2, 12, 32], [1, 1], [2, 2], 'VALID',
                      'NHWC', [4, 16, 16, 12])
    # output channel is 1
    _test_convolution('conv_transpose', [1, 8, 8, 19], [1, 1, 1, 19], [1, 1], [1, 1], 'VALID',
                      'NHWC', [1, 8, 8, 1])
404

405 406 407 408

#######################################################################
# BiasAdd
# -----------
409 410


411 412 413 414 415 416
def _test_biasadd(tensor_in_sizes, data_format):
    """ One iteration of biasadd with given shapes and attributes """

    total_size_1 = 1
    for s in tensor_in_sizes:
        total_size_1 *= s
417 418
    tensor_bias_sizes = [tensor_in_sizes[1]
                         ] if data_format == 'NCHW' else [tensor_in_sizes[3]]
419 420 421 422 423 424 425 426
    total_size_2 = tensor_bias_sizes[0]
    # Initializes the input tensor with array containing incrementing
    # numbers from 1.
    data_array = [f * 1.0 for f in range(1, total_size_1 + 1)]
    bias_array = [f * 1.0 for f in range(1, total_size_2 + 1)]

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=tensor_in_sizes, dtype='float32')
427 428
        in_bias = constant_op.constant(
            bias_array, shape=tensor_bias_sizes, dtype='float32')
429 430 431 432 433 434 435
        nn_ops.bias_add(in_data,
                        in_bias,
                        data_format=data_format)

        compare_tf_with_tvm(np.reshape(data_array, tensor_in_sizes).astype('float32'),
                            'Placeholder:0', 'BiasAdd:0')

436

437 438 439 440 441 442 443 444 445 446 447
def test_forward_biasadd():
    if is_gpu_available():
        _test_biasadd([4, 176, 8, 8], 'NCHW')
        _test_biasadd([1, 100, 1, 1], 'NCHW')
        _test_biasadd([4, 19, 17, 17], 'NCHW')
        _test_biasadd([4, 124, 3, 3], 'NCHW')

    _test_biasadd([4, 8, 8, 176], 'NHWC')
    _test_biasadd([1, 1, 1, 100], 'NHWC')
    _test_biasadd([4, 17, 17, 19], 'NHWC')
    _test_biasadd([4, 3, 3, 124], 'NHWC')
448

449

Wei Chen committed
450 451
def _test_forward_where(input_shape):
    with tf.Graph().as_default():
452
        dtype = tf.float32
Wei Chen committed
453 454 455 456 457 458
        t = tf.constant(np.random.choice([0, 1, -2, 3, -1, 0.1, -0.2],
                                         size=input_shape).astype(dtype.name))
        out = tf.where(t)
        compare_tf_with_tvm([], [], out.name, mode='debug')
        compare_tf_with_tvm([], [], out.name, mode='vm')

459

Wei Chen committed
460 461 462 463 464 465 466
def test_forward_argwhere():
    _test_forward_where((5,))
    _test_forward_where((5, 5))
    _test_forward_where((5, 5, 5))
    _test_forward_where((5, 5, 5, 5))
    _test_forward_where((5, 5, 5, 5, 5))

467
#######################################################################
468 469
# SpaceToBatchND
# --------------
470 471


472 473 474 475 476 477 478 479 480
def _test_space_to_batch_nd(input_shape, block_shape, paddings, dtype='int32'):
    data = np.random.uniform(0, 5, size=input_shape).astype(dtype)

    with tf.Graph().as_default():
        in_data = tf.placeholder(shape=input_shape, dtype=dtype)
        out = tf.space_to_batch_nd(in_data, block_shape, paddings)

        compare_tf_with_tvm(data, in_data.name, out.name)

481

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
def test_forward_space_to_batch_nd():
    # test cases: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/space-to-batch-n-d
    _test_space_to_batch_nd(
        input_shape=[1, 2, 2, 1],
        block_shape=[2, 2],
        paddings=[[0, 0], [0, 0]]
    )

    _test_space_to_batch_nd(
        input_shape=[1, 2, 2, 3],
        block_shape=[2, 2],
        paddings=[[0, 0], [0, 0]]
    )

    _test_space_to_batch_nd(
        input_shape=[1, 4, 4, 1],
        block_shape=[2, 2],
        paddings=[[0, 0], [0, 0]]
    )

    _test_space_to_batch_nd(
        input_shape=[2, 2, 4, 1],
        block_shape=[2, 2],
        paddings=[[0, 0], [2, 0]],
        dtype='int64'
    )

    # pylint: disable=line-too-long
    # https://github.com/tensorflow/tensorflow/blob/24f578/tensorflow/python/kernel_tests/spacetobatch_op_test.py
    _test_space_to_batch_nd(
        input_shape=[2, 3],
        block_shape=[2],
        paddings=[[1, 0]],
        dtype='float32'
    )

    _test_space_to_batch_nd(
        input_shape=[2, 3, 2],
        block_shape=[2],
        paddings=[[1, 0]],
        dtype='float64'
    )

#######################################################################
# BatchToSpaceND
# --------------
528 529


530 531 532 533 534 535 536 537 538
def _test_batch_to_space_nd(input_shape, block_shape, crops, dtype='int32'):
    data = np.random.uniform(0, 5, size=input_shape).astype(dtype)

    with tf.Graph().as_default():
        in_data = tf.placeholder(shape=input_shape, dtype=dtype)
        out = tf.batch_to_space_nd(in_data, block_shape, crops)

        compare_tf_with_tvm(data, in_data.name, out.name)

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 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
def test_forward_batch_to_space_nd():
    # test cases: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/batch-to-space-n-d
    _test_batch_to_space_nd(
        input_shape=[4, 1, 1, 1],
        block_shape=[2, 2],
        crops=[[0, 0], [0, 0]]
    )

    _test_batch_to_space_nd(
        input_shape=[4, 1, 1, 3],
        block_shape=[2, 2],
        crops=[[0, 0], [0, 0]]
    )

    _test_batch_to_space_nd(
        input_shape=[4, 2, 2, 1],
        block_shape=[2, 2],
        crops=[[0, 0], [0, 0]]
    )

    _test_batch_to_space_nd(
        input_shape=[8, 1, 3, 1],
        block_shape=[2, 2],
        crops=[[0, 0], [2, 0]],
        dtype='int64'
    )

    # pylint: disable=line-too-long
    # https://github.com/tensorflow/tensorflow/blob/24f578/tensorflow/python/kernel_tests/batchtospace_op_test.py
    _test_batch_to_space_nd(
        input_shape=[18, 2, 1, 2],
        block_shape=[2, 3],
        crops=[[1, 1], [0, 0]],
        dtype='float32'
    )

    _test_batch_to_space_nd(
        input_shape=[20, 5, 8, 7],
        block_shape=[2, 2],
        crops=[[1, 1], [1, 1]],
        dtype='float64'
    )

#######################################################################
584 585 586
# Reshape
# -------

587

588 589 590 591 592 593 594 595 596
def _test_reshape(data, out_shape):
    """ One iteration of reshape operation with given data and out shape """

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
        array_ops.reshape(in_data, out_shape)

        compare_tf_with_tvm(data, 'Placeholder:0', 'Reshape:0')

Yao Wang committed
597 598 599 600 601 602 603 604 605 606 607
def _test_reshape_with_call():
    """ relay.expr.Call as shape """
    data = np.zeros((6, 4, 2))
    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
        out_shape = tf.constant([1, 2, 3], dtype="int32")
        out_shape = tf.multiply(out_shape, 2)
        array_ops.reshape(in_data, out_shape)

        compare_tf_with_tvm(data, 'Placeholder:0', 'Reshape:0')

608 609 610 611 612 613 614 615 616 617
def _test_reshape_like(data, shape_like):
    """ A special case for reshape. """

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
        in_shape_like = array_ops.placeholder(shape=shape_like.shape, dtype=data.dtype)
        out_shape = array_ops.shape(in_shape_like)
        array_ops.reshape(in_data, out_shape)

        compare_tf_with_tvm(data, 'Placeholder:0', 'Reshape:0')
618

619 620 621 622 623
def test_forward_reshape():
    _test_reshape(np.arange(6.0), [2, 3])
    _test_reshape(np.arange(6), [-1, 2])
    _test_reshape(np.arange(6), [3, -1])
    _test_reshape(np.arange(6), [-1])
Yao Wang committed
624
    _test_reshape_with_call()
625
    _test_reshape_like(np.zeros((3, 6)), np.zeros((9, 2)))
626 627

#######################################################################
628 629 630
# DepthToSpace
# ------------

631

632 633 634 635 636 637 638 639 640
def _test_depthtospace(data, block_size):
    """ One iteration of depth_to_space operation with given data and block size """

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
        array_ops.depth_to_space(in_data, block_size)

        compare_tf_with_tvm(data, 'Placeholder:0', 'DepthToSpace:0')

641

642 643 644 645
def test_forward_depthtospace():
    _test_depthtospace(np.random.normal(size=[1, 32, 32, 4]), 2)
    _test_depthtospace(np.random.normal(size=[1, 16, 8, 32]), 4)

646 647 648 649
#######################################################################
# SpaceToDepth
# ------------

650

651 652 653 654 655 656 657 658 659
def _test_spacetodepth(data, block_size):
    """ One iteration of space_to_depth operation with given data and block size """

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
        array_ops.space_to_depth(in_data, block_size)

        compare_tf_with_tvm(data, 'Placeholder:0', 'SpaceToDepth:0')

660

661 662 663
def test_forward_spacetodepth():
    _test_spacetodepth(np.random.normal(size=[1, 32, 32, 4]), 2)
    _test_spacetodepth(np.random.normal(size=[1, 16, 8, 32]), 4)
664

665 666 667 668
#######################################################################
# Squeeze
# -------

669

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
def _test_squeeze(data, squeeze_dims=None):
    """ One iteration of squeeze """

    if squeeze_dims is None:
        squeeze_dims = []

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)

        if squeeze_dims:
            array_ops.squeeze(in_data, squeeze_dims)
        else:
            array_ops.squeeze(in_data)

        compare_tf_with_tvm(data, 'Placeholder:0', 'Squeeze:0')

686

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
def test_forward_squeeze():
    """ Squeeze """

    # Nothing to squeeze.
    _test_squeeze(np.arange(2).reshape((2)))
    _test_squeeze(np.arange(6).reshape((2, 3)))

    # Squeeze the middle element away.
    _test_squeeze(np.arange(4).reshape((2, 1, 2)))

    # Squeeze on both ends.
    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)))

    # Positive squeeze dim index.
    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [0])
    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [2, 4])
    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [0, 4, 2])

    # Negative squeeze dim index.
    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [-1])
    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [-3, -5])
    _test_squeeze(np.arange(6).reshape((1, 2, 1, 3, 1)), [-3, -5, -1])

710

711 712 713
def test_tensor_array_constructor():
    def run(dtype_str):
        with tf.Graph().as_default():
714 715 716 717
            dtype = tf_dtypes[dtype_str]
            t = tf.constant(np.array([[1.0, 2.0], [3.0, 4.0]]).astype(dtype_str), dtype=dtype)
            t2 = tf.constant(np.array([[1.0, 2.0], [3.0, 4.0]]).astype(dtype_str), dtype=dtype)
            ta1 = tf.TensorArray(dtype=dtype, size=2, infer_shape=False, dynamic_size=False)
718 719 720 721 722
            ta2 = ta1.write(0, t)
            ta3 = ta2.write(1, t2)
            out = ta3.read(0)
            g = tf.get_default_graph()
            compare_tf_with_tvm([], [], 'TensorArrayReadV3:0', mode='debug')
723 724
    for dtype in tf_dtypes.keys():
        run(dtype)
725

726

727 728 729
def test_tensor_array_scatter():
    def run(dtype_str):
        with tf.Graph().as_default():
730 731
            dtype =  tf_dtypes[dtype_str]
            t = tf.constant(np.array([[1.0], [2.0], [3.0]]).astype(dtype_str), dtype=dtype)
732
            indices = tf.constant([2, 1, 0])
733 734
            ta1 = tf.TensorArray(dtype=dtype, size=3,
                                 infer_shape=False, dynamic_size=False)
735 736 737 738 739 740
            ta2 = ta1.scatter(indices, t)
            out0 = ta2.read(0)
            out1 = ta2.read(1)
            out2 = ta2.read(2)
            g = tf.get_default_graph()
            compare_tf_with_tvm([], [], ['TensorArrayReadV3:0'], mode='debug')
741 742 743 744
            compare_tf_with_tvm([], [], ['TensorArrayReadV3_1:0'], mode='debug')
            compare_tf_with_tvm([], [], ['TensorArrayReadV3_2:0'], mode='debug')
    for dtype in tf_dtypes.keys():
        run(dtype)
745 746 747 748 749 750 751 752 753 754 755 756 757 758

# TODO(wweic): Fix gather issue with PartialEvaluate
# def test_tensor_array_gather():
#     with tf.Graph().as_default():
#         dtype = 'float32'
#         t = tf.constant([[1.0], [2.0], [3.0]])
#         scatter_indices = tf.constant([2, 1, 0])
#         gather_indices = tf.constant([1, 2])
#         ta1 = tf.TensorArray(dtype=tf.float32, size=3, infer_shape=False, dynamic_size=False)
#         ta2 = ta1.scatter(scatter_indices, t)
#         t1 = ta2.gather(gather_indices)
#         g = tf.get_default_graph()
#         compare_tf_with_tvm([], [], ['TensorArrayGatherV3:0'], mode='debug')

759

760 761 762
def test_tensor_array_split():
    def run(dtype_str):
        with tf.Graph().as_default():
763 764
            dtype =  tf_dtypes[dtype_str]
            t = tf.constant(np.array([[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0]]).astype(dtype_str), dtype=dtype)
765
            split_length = tf.constant([2, 2, 2, 2], dtype=tf.int32)
766 767
            ta1 = tf.TensorArray(dtype=dtype, size=4,
                                 infer_shape=False, dynamic_size=False)
768 769 770 771 772 773 774
            ta2 = ta1.split(t, split_length)
            out0 = ta2.read(0)
            out1 = ta2.read(1)
            out2 = ta2.read(2)
            out3 = ta2.read(3)
            g = tf.get_default_graph()
            compare_tf_with_tvm([], [], ['TensorArrayReadV3:0'], mode='debug')
775 776 777 778 779
            compare_tf_with_tvm([], [], ['TensorArrayReadV3_1:0'], mode='debug')
            compare_tf_with_tvm([], [], ['TensorArrayReadV3_2:0'], mode='debug')
            compare_tf_with_tvm([], [], ['TensorArrayReadV3_3:0'], mode='debug')
    for dtype in tf_dtypes.keys():
        run(dtype)
780

781

782 783 784
def test_tensor_array_concat():
    def run(dtype_str):
        with tf.Graph().as_default():
785 786
            dtype = tf_dtypes[dtype_str]
            t = tf.constant(np.array([[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0]]).astype(dtype_str), dtype=dtype)
787
            split_length = tf.constant([2, 2, 2, 2], dtype=tf.int32)
788 789
            ta1 = tf.TensorArray(dtype=dtype, size=4,
                                 infer_shape=False, dynamic_size=False)
790 791
            ta2 = ta1.split(t, split_length)
            t = ta2.concat()
792 793
            out = tf.identity(t)
            compare_tf_with_tvm([], [], ['Identity:0'], mode='debug')
794 795
    for dtype in tf_dtypes.keys():
        run(dtype)
796

797

798 799 800
def test_tensor_array_size():
    def run(dtype_str):
        with tf.Graph().as_default():
801 802
            dtype =  tf_dtypes[dtype_str]
            ta1 = tf.TensorArray(dtype=dtype, size=2, infer_shape=False, dynamic_size=False)
803 804 805
            out = ta1.size()
            g = tf.get_default_graph()
            compare_tf_with_tvm([], [], 'TensorArraySizeV3:0', mode='debug')
806 807
    for dtype in tf_dtypes.keys():
        run(dtype)
808

809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
def test_tensor_array_unstack():
    def run(dtype_str, input_shape):
        with tf.Graph().as_default():
            dtype = tf_dtypes[dtype_str]
            t = tf.constant(np.random.choice([0, 1, 2, 3],
                                             size=input_shape).astype(dtype.name))
            ta1 = tf.TensorArray(dtype=dtype, infer_shape=False, size=input_shape[0])
            ta2 = ta1.unstack(t)
            out0 = ta2.size()
            out1 = ta2.read(0)
            compare_tf_with_tvm([], [], 'TensorArraySizeV3:0', mode='debug')
            compare_tf_with_tvm([], [], 'TensorArrayReadV3:0', mode='debug')
    for dtype in tf_dtypes.keys():
        run(dtype, (5,))
        run(dtype, (5, 5))
        run(dtype, (5, 5, 5))
        run(dtype, (5, 5, 5, 5))
        run(dtype, (5, 5, 5, 5, 5))
        run(dtype, (5, 5, 5, 5, 5, 5))

829 830 831 832
#######################################################################
# ConcatV2
# --------

833

834
def _test_concat_v2(shape1, shape2, dim):
835 836 837
    """ One iteration of ConcatV2 """

    with tf.Graph().as_default():
838 839 840 841
        dtype = 'float32'
        in1 = tf.placeholder(shape=shape1, dtype=dtype, name='in1')
        in2 = tf.placeholder(shape=shape2, dtype=dtype, name='in2')
        array_ops.concat_v2([in1, in2], dim)
842

843 844
        np_data1 = np.random.uniform(size=shape1).astype(dtype)
        np_data2 = np.random.uniform(size=shape2).astype(dtype)
845

846 847 848
        compare_tf_with_tvm([np_data1, np_data2], [
                            'in1:0', 'in2:0'], 'ConcatV2:0')

849

850 851 852
def test_forward_concat_v2():
    if tf.__version__ < LooseVersion('1.4.1'):
        return
853

854 855 856 857 858
    _test_concat_v2([2, 3], [2, 3], 0)
    _test_concat_v2([10, 3, 5], [2, 3, 5], 0)
    _test_concat_v2([2, 3], [2, 3], 1)
    _test_concat_v2([5, 8], [5, 4], 1)
    _test_concat_v2([2, 8, 5], [2, 8, 6], -1)
859 860 861 862 863

#######################################################################
# Sigmoid
# -------

864

865 866 867 868 869 870 871 872 873
def _test_sigmoid(data):
    """ One iteration of sigmoid """

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
        sigmoid_out = math_ops.sigmoid(in_data)

        compare_tf_with_tvm(data, 'Placeholder:0', 'Sigmoid:0')

874

875 876 877 878 879 880 881 882 883
def test_forward_sigmoid():
    """ Sigmoid """

    _test_sigmoid(np.random.uniform(size=(3, 4, 4, 3)).astype('float32'))

#######################################################################
# Argmin/Argmax
# -------------

884

885 886 887
def _test_argx(func, data, **kwargs):

    with tf.Graph().as_default():
888 889
        inp = array_ops.placeholder(
            shape=data.shape, dtype=data.dtype, name="c0")
890 891 892 893
        func(inp, name="argx0", output_type=tf.int32, **kwargs)

        compare_tf_with_tvm(data, 'c0:0', 'argx0:0')

894

895
def test_forward_argminmax():
896 897
    for axis in [None, 0, 1, 2]:
        data = np.random.uniform(size=(8, 4, 9)).astype('float32')
898 899 900 901 902 903 904
        _test_argx(tf.argmax, data=data, axis=axis)
        _test_argx(tf.argmin, data=data, axis=axis)

#######################################################################
# Reduce
# ------

905

906 907 908 909
def _test_reduce(func, data, **kwargs):
    """ One iteration of a reduce operation"""

    with tf.Graph().as_default():
910 911
        inp = array_ops.placeholder(
            shape=data.shape, dtype=data.dtype, name="c0")
912 913 914 915
        func(inp, name="reducex0", **kwargs)

        compare_tf_with_tvm(data, 'c0:0', 'reducex0:0')

916

917
def test_forward_reduce():
918
    data = np.random.uniform(size=(8, 4, 9)).astype('float32')
919 920
    _test_reduce(tf.reduce_sum, data=data)
    _test_reduce(tf.reduce_sum, data=data, axis=0)
921
    _test_reduce(tf.reduce_sum, data=data, axis=(0, 1))
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940


#######################################################################
# Variable
# --------

def _test_variable(data):
    """ One iteration of a variable """

    tf.reset_default_graph()
    input_op = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
    input_tensor = array_ops.reshape(input_op, data.shape)

    size = input_tensor.shape.dims[1]
    with variable_scope.variable_scope("linear", reuse=None):
        w = variable_scope.get_variable(
            "w", shape=[size, size], dtype=input_tensor.dtype)
    math_ops.matmul(input_tensor, w)

941 942 943
    compare_tf_with_tvm(data, 'Placeholder:0', 'MatMul:0',
                        init_global_variables=True)

944 945 946 947 948 949 950

def test_forward_variable():
    """Variable type op test"""
    _test_variable(np.random.uniform(size=(32, 100)).astype('float32'))


#######################################################################
951 952
# MatMul, BatchMatMul, BatchMatMulV2
# ----------------------------------
953 954 955 956 957 958 959 960 961 962

def _test_matmul(i, j, k, dtype, outer=None):
    """ One iteration of matmul """

    A_shape_init = [i, j]
    B_shape_init = [j, k]

    for transpose_a in [False, True]:
        for transpose_b in [False, True]:
            outer = outer or []
963 964 965 966
            A_shape = outer + \
                (A_shape_init[::-1] if transpose_a else A_shape_init)
            B_shape = outer + \
                (B_shape_init[::-1] if transpose_b else B_shape_init)
967 968 969 970

            with tf.Graph().as_default():
                A = tf.placeholder(shape=A_shape, dtype=dtype, name='A')
                B = tf.placeholder(shape=B_shape, dtype=dtype, name='B')
971 972
                result = tf.matmul(
                    A, B, transpose_a=transpose_a, transpose_b=transpose_b)
973 974 975

                A_np = np.random.uniform(high=5.0, size=A_shape).astype(dtype)
                B_np = np.random.uniform(high=5.0, size=B_shape).astype(dtype)
976 977 978
                compare_tf_with_tvm(
                    [A_np, B_np], [A.name, B.name], result.name)

979 980

def test_forward_matmul():
981
    """ MatMul op test"""
982 983
    _test_matmul(1, 3, 6, 'int32')
    _test_matmul(5, 3, 1, 'float64')
984

985

986 987 988 989 990 991 992 993 994 995 996 997
def _test_batch_matmul(A_shape, B_shape, dtype, adjoint_a=False, adjoint_b=False):

    with tf.Graph().as_default():
        A = tf.placeholder(shape=A_shape, dtype=dtype, name='A')
        B = tf.placeholder(shape=B_shape, dtype=dtype, name='B')
        result = tf.matmul(A, B, adjoint_a=adjoint_a,
                           adjoint_b=adjoint_b, name='batchmatmul')

        A_np = np.random.uniform(high=5.0, size=A_shape).astype(dtype)
        B_np = np.random.uniform(high=5.0, size=B_shape).astype(dtype)
        compare_tf_with_tvm([A_np, B_np], [A.name, B.name], result.name)

998

999 1000 1001 1002 1003 1004
def test_forward_batch_matmul():
    """ TF op BatchMatMul, BatchMatMulV2 test"""
    _test_batch_matmul((3, 5, 4), (3, 4, 5), 'int32')
    _test_batch_matmul((3, 5, 4), (3, 4, 5), 'float32', True, True)
    _test_batch_matmul((3, 5, 4), (3, 5, 4), 'int32', True, False)
    _test_batch_matmul((3, 5, 4), (3, 5, 4), 'float32', False, True)
1005
    _test_batch_matmul((2, 3, 4, 5, 6), (2, 3, 4, 6, 5), 'int32')
1006 1007
    _test_batch_matmul((1, 2, 3, 4, 5, 6),
                       (1, 2, 3, 4, 6, 5), 'float32', True, True)
1008
    _test_batch_matmul((3, 4, 5, 6), (3, 4, 5, 6), 'int32', True, False)
1009 1010
    _test_batch_matmul((2, 3, 4, 2, 3, 4, 5, 6),
                       (2, 3, 4, 2, 3, 4, 5, 6), 'float32', False, True)
1011 1012 1013


#######################################################################
1014 1015 1016 1017
# StridedSlice
# ------------

def _test_stridedslice(ip_shape, begin, end, stride, dtype,
1018 1019
                       begin_mask=0, end_mask=0, new_axis_mask=0,
                       shrink_axis_mask=0, ellipsis_mask=0):
1020 1021 1022 1023 1024
    """ One iteration of a Stridedslice """

    tf.reset_default_graph()
    in_data = tf.placeholder(dtype, ip_shape, name="in_data")
    tf.strided_slice(in_data, begin, end, stride, begin_mask=begin_mask,
1025 1026 1027
                     end_mask=end_mask, new_axis_mask=new_axis_mask,
                     shrink_axis_mask=shrink_axis_mask,
                     ellipsis_mask=ellipsis_mask, name="strided_slice")
1028 1029 1030 1031
    np_data = np.random.uniform(size=ip_shape).astype(dtype)

    compare_tf_with_tvm(np_data, 'in_data:0', 'strided_slice:0')

1032

1033 1034 1035
def test_forward_stridedslice():
    '''test StridedSlice'''

1036
    _test_stridedslice((2), [1], [1], [1], 'float32', shrink_axis_mask=1)
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
    _test_stridedslice((3, 4, 3), [1, -1, 0],
                       [4, -5, 3], [2, -1, 1], 'float32')
    _test_stridedslice((3, 4, 3), [1, 0], [4, 3], [
                       2, 1], 'float32', ellipsis_mask=8)
    _test_stridedslice((3, 4, 3), [1, 0], [4, 2], [
                       2, 1], 'float32', ellipsis_mask=2)
    _test_stridedslice((3, 4, 5, 3), [1, 0], [4, 2], [
                       2, 1], 'float32', ellipsis_mask=2)
    _test_stridedslice((3, 4, 5, 3), [1, 0, 1], [4, 2, 2], [
                       2, 1, 1], 'float32', ellipsis_mask=2)
    _test_stridedslice((3, 4, 3), [1, 1, 0], [4, 4, 2], [
                       2, 1, 1], 'float32', new_axis_mask=5)
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
    _test_stridedslice((3, 4, 3), [1, 1, 1], [4, 4, 1], [2, 1, 1], 'float32', ellipsis_mask=2,
                       new_axis_mask=4)
    _test_stridedslice((6, 4, 5), [1, 1, 1], [6, 3, 4], [2, 1, 1], 'float32', ellipsis_mask=2,
                       new_axis_mask=5)
    _test_stridedslice((3, 4, 3), [1, 1, 2], [4, 4, 3], [2, 1, 1], 'float32', ellipsis_mask=4,
                       new_axis_mask=2)
    _test_stridedslice((3, 4, 3), [1, 1, 2], [4, 4, 3], [2, 1, 1], 'float32', ellipsis_mask=2,
                       new_axis_mask=3)
    _test_stridedslice((3, 4, 3), [1, 1, 0], [4, 4, 1], [2, 1, 1], 'float32', ellipsis_mask=2,
                       new_axis_mask=3)
    _test_stridedslice((3, 4, 3), [1, 1, 2], [4, 4, 3], [2, 1, 1], 'float32', ellipsis_mask=2,
                       new_axis_mask=2)
1061 1062
    _test_stridedslice((3, 4), [1, 0], [4, 4], [
                       1, 1], 'float32', shrink_axis_mask=2)
1063 1064 1065 1066 1067 1068 1069 1070
    _test_stridedslice((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1], 'float32', shrink_axis_mask=2,
                       new_axis_mask=2)
    _test_stridedslice((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1], 'float32', shrink_axis_mask=1,
                       new_axis_mask=2)
    _test_stridedslice((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1], 'float32', shrink_axis_mask=2,
                       new_axis_mask=1)
    _test_stridedslice((3, 4, 5, 4, 5, 6), [0, 0], [2, 3], [1, 1], 'float32', shrink_axis_mask=5,
                       new_axis_mask=1)
1071
    _test_stridedslice((3, 4, 5, 4, 5, 6), [0, 0, 1, 2, 1], [2, 3, 4, 5, 3], [1, 1, 2, 2, 1],
1072 1073
                       'float32', shrink_axis_mask=5, new_axis_mask=1, ellipsis_mask=2,
                       begin_mask=8, end_mask=8)
1074
    _test_stridedslice((3, 4, 5, 4, 5, 6), [0, 0, 1, 2, 1], [2, 3, 4, 5, 3], [1, 1, 2, 2, 1],
1075 1076
                       'float32', shrink_axis_mask=8, new_axis_mask=1, ellipsis_mask=2,
                       begin_mask=5, end_mask=5)
1077
    _test_stridedslice((3, 4, 5, 4, 5, 6), [0, 0, 1, 2, 1], [2, 3, 4, 5, 3], [1, 1, 2, 2, 1],
1078 1079
                       'float32', shrink_axis_mask=16, new_axis_mask=1, ellipsis_mask=2,
                       begin_mask=5, end_mask=5)
1080
    _test_stridedslice((3, 4, 5, 4, 5, 6), [1, 2, 0, -3], [4, 5, 3, 3], [2, 2, 1, 1],
1081 1082
                       'float32', shrink_axis_mask=8, new_axis_mask=1, ellipsis_mask=2,
                       begin_mask=5, end_mask=8)
1083

1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
#######################################################################
# FloorDiv, RealDiv
# -----------------
def _test_forward_divide(ip_shape, dtype):
    np_numer = np.random.uniform(-100, 100, size=ip_shape).astype(dtype)
    np_denomin = np.random.uniform(1, 100, size=ip_shape).astype(dtype)
    tf.reset_default_graph()
    numerator = tf.placeholder(dtype, ip_shape, name="numer")
    denominator = tf.placeholder(dtype, ip_shape, name="denomin")
    tf.math.divide(numerator, denominator, name='RealDiv')
1094 1095 1096
    compare_tf_with_tvm([np_numer, np_denomin], [
                        'numer:0', 'denomin:0'], 'RealDiv:0')

1097 1098

def _test_forward_floordiv(ip_shape, dtype):
1099
    np_numer = np.random.uniform(1, 100, size=ip_shape).astype(dtype)
1100 1101 1102 1103 1104
    tf.reset_default_graph()
    numerator = tf.placeholder(dtype, ip_shape, name="numer")
    tf.math.floordiv(numerator, tf.constant(5, dtype=dtype), name='FloorDiv')
    compare_tf_with_tvm([np_numer], ['numer:0'], 'FloorDiv:0')

1105

1106 1107 1108 1109 1110
def test_forward_divide():
    '''test FloorDiv, RealDiv'''
    _test_forward_divide((4,), 'int32')
    _test_forward_divide((4, 3, 7), 'float32')
    _test_forward_floordiv((4, 3, 7), 'float32')
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
    _test_forward_floordiv((4, 3, 7), 'int32')

#######################################################################
# FloorMod
# --------
def _test_forward_floormod(in_shape, if_shape, dtype):
    np_numer = np.random.uniform(1, 100, size=in_shape).astype(dtype)
    np_factor = np.random.uniform(1, 100, size=if_shape).astype(dtype)
    tf.reset_default_graph()
    numerator = tf.placeholder(dtype, in_shape, name="numer")
    factor = tf.placeholder(dtype, if_shape, name="factor")
    tf.floormod(numerator, factor, name='FloorMod')
    compare_tf_with_tvm([np_numer, np_factor], ['numer:0', 'factor:0'], 'FloorMod:0')

def test_forward_floormod():
    '''test FloorMod'''
    _test_forward_floormod((10,), (10,), 'float32')
    _test_forward_floormod((8, 2), (1,), 'float32')
    _test_forward_floormod((4, 3, 7), (4, 3, 7), 'float32')
    _test_forward_floormod((4, 3, 7), (4, 3, 7), 'int32')
1131

1132 1133

#######################################################################
1134 1135 1136 1137 1138 1139 1140 1141 1142
# TruncateMod
# -----------
def _test_forward_truncatemod(ip_shape, dtype):
    np_data_1 = np.random.uniform(-100, 100, size=ip_shape).astype(dtype)
    np_data_2 = np.random.uniform(1, 10, size=ip_shape).astype(dtype)
    tf.reset_default_graph()
    in_data_1 = tf.placeholder(dtype, ip_shape, name="in_data_1")
    in_data_2 = tf.placeholder(dtype, ip_shape, name="in_data_2")
    tf.truncatemod(in_data_1, in_data_2, name='truncatemod')
1143 1144 1145
    compare_tf_with_tvm([np_data_1, np_data_2], [
                        'in_data_1:0', 'in_data_2:0'], 'truncatemod:0')

1146 1147 1148 1149 1150 1151 1152 1153 1154

def test_forward_truncatemod():
    '''test TruncateMod'''
    _test_forward_truncatemod((4, 3, 7), 'int32')


#######################################################################
# Gather, GatherV2, GatherNd
# --------------------------
1155 1156

def _test_gather(ip_shape, indice_shape, indice_value, axis, dtype):
1157
    """ One iteration of a GatherV2 """
1158 1159 1160 1161

    tf.reset_default_graph()
    in_data = tf.placeholder(dtype, ip_shape, name="in_data")
    indices = tf.placeholder("int32", indice_shape, name="indices")
1162
    out = tf.gather(in_data, indices, axis=axis)
1163
    np_data = np.random.uniform(1, 10, size=ip_shape).astype(dtype)
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

    def _fill_indices(indice_value):
        indices = np.array(ip_shape, dtype=dtype)
        if isinstance(indice_value, int):
            indices = np.array([indice_value], dtype='int32')
        else:
            indices = np.asarray(indice_value, dtype='int32')
        return indices
    np_indices = _fill_indices(indice_value)

1174 1175 1176
    compare_tf_with_tvm([np_data, np_indices], [
                        'in_data:0', 'indices:0'], out.name)

1177 1178

def test_forward_gather():
1179
    '''test Gather/GatherV2 layer'''
1180 1181
    _test_gather((4,), (1,), 1, 0, 'int32')
    _test_gather((4,), (1,), 1, 0, 'float32')
1182
    _test_gather((1, 4), (1,), [0], 0, 'int32')
1183 1184 1185 1186
    _test_gather((4,), (1, 2, 2), [[[1, 0], [0, 1]]], 0, 'float32')
    _test_gather((2, 2), (1, 2, 2), [[[1, 0], [0, 1]]], 0, 'int32')
    _test_gather((2, 2), (1, 2, 2), [[[1, 0], [0, 1]]], 1, 'int32')
    _test_gather((2, 2), (1, 2, 2), [[[1, 0], [0, 1]]], 0, 'float32')
1187 1188 1189
    _test_gather((3, 3, 3), (1, 1, 2), [[[1, 0]]], 0, 'int32')
    _test_gather((3, 3, 3), (1, 1, 2), [[[1, 0]]], 2, 'int32')
    _test_gather((4, 3, 5, 6), (1, 4), [[2, 1, 0, 0]], 0, 'float32')
1190

1191

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
def test_forward_gather_nd():
    """test operator GatherNd"""
    np_data = np.random.uniform(1, 100, size=(2, 2)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (2, 2), name="in_data")
    tf.gather_nd(in_data, indices=[[1, 0], [0, 1]], name="gather_nd")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'gather_nd:0')


#######################################################################
# BiasAdd
# -------
def test_forward_bias_add():
    """test Op BiasAdd"""
    def check_bias_add(lh_shpae, rh_shape, dtype):
        tf.reset_default_graph()
        lh_data = np.random.uniform(size=lh_shpae).astype(dtype)
        rh_data = np.random.uniform(size=rh_shape).astype(dtype)
        lft_data = tf.placeholder(dtype, name="lft_data")
        rgt_data = tf.placeholder(dtype, name="rgt_data")
        tf.nn.bias_add(lft_data, rgt_data, name="BiasAdd")
1213 1214
        compare_tf_with_tvm([lh_data, rh_data], [
                            'lft_data:0', 'rgt_data:0'], 'BiasAdd:0')
1215 1216 1217 1218 1219

    check_bias_add((10, 8, 16, 32), (32,), dtype="int32")
    check_bias_add((10, 20), (20,), dtype="float32")


1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
#######################################################################
# Split
# -----

def _test_split(in_shape, axis, num_or_size_splits, dtype):
    np_data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)

    """ One iteration of a Split """
    tf.reset_default_graph()
    in_data = tf.placeholder(dtype, in_shape, name="in_data")
1230
    num_split = len(num_or_size_splits) if isinstance(num_or_size_splits, list)\
1231
        else num_or_size_splits
1232 1233
    split = tf.split(in_data, num_or_size_splits, axis=axis)
    relu = [tf.nn.relu(i) for i in split]
1234

1235
    compare_tf_with_tvm([np_data], ['in_data:0'], [n.name for n in relu])
1236 1237 1238 1239 1240 1241 1242 1243 1244

    # and now test together with concat
    tf.reset_default_graph()
    in_data = tf.placeholder(dtype, in_shape, name="in_data")
    splitted = tf.split(in_data, num_or_size_splits, axis=axis)
    tf.concat(splitted, axis)

    compare_tf_with_tvm([np_data], 'in_data:0', 'concat:0')

1245

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
def test_forward_split():
    '''test split layer'''
    # rank 1
    _test_split((3,), 0, 1, 'float32')
    _test_split((3,), 0, 3, 'float32')
    _test_split((6,), 0, 3, 'float32')
    # rank 2
    _test_split((6, 2), 0, 3, 'float32')
    _test_split((2, 6), 1, 6, 'float32')
    # rank 3
    _test_split((6, 2, 4), 0, 2, 'int32')
    _test_split((2, 6, 4), 1, 3, 'float32')
    _test_split((2, 4, 6), 2, 1, 'float32')
    # rank 4
    _test_split((6, 1, 3, 5), 0, 3, 'float32')
    _test_split((1, 6, 3, 5), 1, 3, 'float32')
    _test_split((1, 3, 6, 5), 2, 3, 'float32')
    _test_split((1, 3, 5, 6), 3, 3, 'float32')
    # split along negative axis
    _test_split((6, 1, 3, 5), -4, 3, 'float32')
    _test_split((1, 6, 3, 5), -3, 3, 'float32')
    _test_split((1, 3, 6, 5), -2, 3, 'float32')
    _test_split((1, 3, 5, 6), -1, 3, 'float32')
    # size_splits list
    _test_split((6,), 0, [1, 2, 3], 'int32')
    _test_split((3, 6, 4), -2, [1, 4, 1], 'float32')


1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
######################################################################
# TopKV2
# ------

def _test_forward_top_k_v2(in_shape, k):
    np_data = np.random.uniform(-100, 100, size=in_shape).astype("float32")
    tf.reset_default_graph()
    in_data = tf.placeholder("float32", in_shape, name="in_data")
    tf.math.top_k(in_data, k, name='TopK')
    compare_tf_with_tvm([np_data], ['in_data:0'], 'TopK:0')

1285

1286 1287 1288 1289 1290 1291 1292
def test_forward_top_k_v2():
    _test_forward_top_k_v2((3,), 1)
    _test_forward_top_k_v2((3,), 3)
    _test_forward_top_k_v2((3, 5, 7), 3)
    _test_forward_top_k_v2((3, 5, 7), 3)


1293 1294 1295 1296 1297 1298 1299 1300 1301
#######################################################################
# Unstack
# -------

def _test_unstack(ip_shape, axis, dtype):
    np_data = np.random.uniform(-5, 5, size=ip_shape).astype(dtype)

    tf.reset_default_graph()
    in_data = tf.placeholder(dtype, ip_shape, name="in_data")
1302
    unstack = tf.unstack(in_data, axis=axis)
1303

1304
    compare_tf_with_tvm([np_data], ['in_data:0'], [n.name for n in unstack])
1305 1306 1307 1308 1309 1310 1311

    tf.reset_default_graph()
    in_data = tf.placeholder(dtype, ip_shape, name="in_data")
    tf.stack(tf.unstack(in_data, axis=axis), axis=axis)

    compare_tf_with_tvm([np_data], ['in_data:0'], 'stack:0')

1312

1313 1314 1315
def test_forward_unstack():
    '''test unstack layer'''
    _test_unstack((6,), 0, 'int32')
1316
    _test_unstack((2, 6), 1, 'float64')
1317
    # negative axis
1318 1319
    _test_unstack((1, 4), -1, 'int32')
    _test_unstack((3, 6, 4), -2, 'float32')
1320

1321 1322

#######################################################################
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
# Tile
# ----

def _test_tile(in_shape, multiples, dtype):
    np_data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)
    tf.reset_default_graph()
    in_data = tf.placeholder(dtype, in_shape, name="in_data")
    tf.tile(in_data, multiples=multiples, name="tile")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'tile:0')

1333

1334 1335 1336 1337 1338 1339 1340 1341
def test_forward_tile():
    '''test Tile'''
    _test_tile((2, ), (3, ), "int32")
    _test_tile((2, 2), (2, 3), "float32")
    _test_tile((2, 4, 6), (6, 7, 8), "float64")


#######################################################################
1342 1343 1344 1345 1346 1347
# ClipByValue
# -----------

def _test_forward_clip_by_value(ip_shape, clip_value_min, clip_value_max, dtype):
    tf.reset_default_graph()
    in_data = tf.placeholder(dtype, ip_shape, name="in_data")
1348 1349
    tf.clip_by_value(in_data, clip_value_min,
                     clip_value_max, name="ClipByValue")
1350 1351 1352
    np_data = np.random.uniform(-100, 100, size=ip_shape).astype(dtype)
    compare_tf_with_tvm([np_data], ['in_data:0'], 'ClipByValue:0')

1353

1354 1355 1356 1357 1358 1359 1360
def test_forward_clip_by_value():
    '''test ClipByValue op'''
    if tf.__version__ < LooseVersion('1.9'):
        _test_forward_clip_by_value((4,), .1, 5., 'float32')
        _test_forward_clip_by_value((4, 4), 1, 5, 'int32')

#######################################################################
1361 1362 1363
# Multi Input to graph
# --------------------

1364

1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
def test_forward_multi_input():
    with tf.Graph().as_default():
        in1 = tf.placeholder(tf.int32, shape=[3, 3], name='in1')
        in2 = tf.placeholder(tf.int32, shape=[3, 3], name='in2')
        in3 = tf.placeholder(tf.int32, shape=[3, 3], name='in3')
        in4 = tf.placeholder(tf.int32, shape=[3, 3], name='in4')

        out1 = tf.add(in1, in2, name='out1')
        out2 = tf.subtract(in3, in4, name='out2')
        out = tf.multiply(out1, out2, name='out')
        in_data = np.arange(9, dtype='int32').reshape([3, 3])

        compare_tf_with_tvm([in_data, in_data, in_data, in_data],
                            ['in1:0', 'in2:0', 'in3:0', 'in4:0'], 'out:0')

#######################################################################
# Multi Output to Graph
# ---------------------

1384

1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
def test_forward_multi_output():
    with tf.Graph().as_default():
        in1 = tf.placeholder(tf.int32, shape=[3, 3], name='in1')
        in2 = tf.placeholder(tf.int32, shape=[3, 3], name='in2')
        in3 = tf.placeholder(tf.int32, shape=[3, 3], name='in3')
        in4 = tf.placeholder(tf.int32, shape=[3, 3], name='in4')

        out1 = tf.add(in1, in2, name='out1')
        out2 = tf.subtract(in3, in4, name='out2')
        in_data = np.arange(9, dtype='int32').reshape([3, 3])
        in_data = [in_data] * 4
        in_name = ['in1:0', 'in2:0', 'in3:0', 'in4:0']
        out_name = ['out1:0', 'out2:0']
        out_node = [out.strip(':0') for out in out_name]
        in_node = [inp.strip(':0') for inp in in_name]
1400

1401 1402 1403 1404 1405 1406 1407
        with tf.Session() as sess:
            final_graph_def = tf.graph_util.convert_variables_to_constants(
                sess, sess.graph.as_graph_def(add_shapes=True), out_node,)
            tf_output = run_tf_graph(sess, in_data, in_name, out_name)
            tvm_output = run_tvm_graph(final_graph_def, in_data, in_node, target='llvm',
                                       out_names=out_node, num_output=2)
            for i in range(len(tf_output)):
1408 1409
                tvm.testing.assert_allclose(
                    tf_output[i], tvm_output[i], atol=1e-5, rtol=1e-5)
1410 1411

#######################################################################
1412 1413
# Resize Bilinear, Nearest_Neighbor
# ---------------------------------
1414

1415

1416 1417 1418 1419 1420 1421 1422 1423
def _test_resize_bilinear(in_shape, to_shape, align_corners):
    """ One iteration of resize bilinear """

    data = np.random.uniform(size=in_shape).astype('float32')
    shape_data = np.array(to_shape).astype('int32')

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
1424 1425
        shape_data = constant_op.constant(
            shape_data, shape=shape_data.shape, dtype=shape_data.dtype)
1426 1427
        tf.image.resize_bilinear(
            in_data, shape_data, align_corners=align_corners)
1428 1429 1430

        compare_tf_with_tvm(data, 'Placeholder:0', 'ResizeBilinear:0')

1431

1432 1433 1434 1435 1436 1437 1438 1439
def _test_resize_bilinear_from_tensor(in_shape, align_corners):
    """ One iteration of resize bilinear with non-constant output shape, requires
        value inference to get proper output shape."""

    data = np.random.uniform(size=in_shape).astype('float32')

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(
1440 1441
            shape=[in_shape[0], None, None, in_shape[3]], dtype=data.dtype)
        to_shape = tf.shape(in_data)[1:3]
1442 1443
        tf.image.resize_bilinear(
            in_data, to_shape, align_corners=align_corners)
1444 1445 1446

        compare_tf_with_tvm(data, 'Placeholder:0', 'ResizeBilinear:0')

1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457

def _test_resize_nearest_neighbor(in_shape, to_shape):
    """ One iteration of resize nearest neighbor """

    data = np.random.uniform(size=in_shape).astype('float32')
    shape_data = np.array(to_shape).astype('int32')

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
        shape_data = constant_op.constant(
            shape_data, shape=shape_data.shape, dtype=shape_data.dtype)
1458 1459
        tf.image.resize_nearest_neighbor(
            in_data, shape_data, name='resize_nearest_neighbor')
1460 1461 1462 1463

        compare_tf_with_tvm(data, 'Placeholder:0', 'resize_nearest_neighbor:0')


1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
def _test_resize_nearest_neighbor_dynamic_shape(in_shape, scale):
    """ One iteration of resize nearest neighbor for graph with dynamic input shape """

    data = np.random.uniform(size=in_shape).astype('float32')
    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=None, dtype=data.dtype)
        # multiply input shape by scale factor
        new_shape = tf.shape(in_data)[1:3] * tf.constant(scale, dtype=tf.int32)
        tf.image.resize_nearest_neighbor(
            in_data, new_shape, name='resize_nearest_neighbor')

        compare_tf_with_tvm(data, 'Placeholder:0', 'resize_nearest_neighbor:0')


1478 1479
def test_forward_resize():
    """ Resize Bilinear, Nearest_Neighbor """
1480 1481 1482 1483 1484 1485 1486
    # TF default layout is NHWC
    _test_resize_bilinear((4, 32, 32, 3), [50, 50], False)
    _test_resize_bilinear((6, 32, 32, 3), [20, 20], True)
    _test_resize_bilinear_from_tensor((4, 32, 32, 3), False)
    _test_resize_bilinear_from_tensor((6, 50, 50, 3), True)
    _test_resize_nearest_neighbor((6, 32, 32, 3), [20, 20])
    _test_resize_nearest_neighbor_dynamic_shape((1, 16, 16, 3), scale=[2, 2])
1487

1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504

#######################################################################
# BroadcastTo
# -----------

def _test_broadcast_to(in_shape, to_shape):
    """ One iteration of broadcast_to"""

    data = np.random.uniform(size=in_shape).astype('float32')
    shape_data = np.array(to_shape).astype('int32')

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
        shape_data = constant_op.constant(
            shape_data, shape=shape_data.shape, dtype=shape_data.dtype)
        tf.broadcast_to(in_data, shape_data)

1505 1506
        compare_tf_with_tvm(data, 'Placeholder:0',
                            'BroadcastTo:0', opt_level=0)
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542


def _test_broadcast_to_from_tensor(in_shape):
    """ One iteration of broadcast_to with unknown shape at graph build"""

    data = np.random.uniform(size=in_shape).astype('float32')

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(
            shape=[None], dtype=data.dtype)

        shape_data = tf.multiply(tf.shape(in_data), 32)
        tf.broadcast_to(in_data, shape_data)

        compare_tf_with_tvm(data, 'Placeholder:0', 'BroadcastTo:0')


def test_forward_broadcast_to():
    """ Resize Bilinear """

    _test_broadcast_to((4, 1, 32, 32), [4, 8, 32, 32])
    _test_broadcast_to((6, 32, 32, 1), [6, 32, 32, 16])
    _test_broadcast_to_from_tensor((1))


#######################################################################
# Fill
# ----

def _test_fill(in_shape):
    """ Use the fill op to create a tensor of ones with non-constant shape."""

    with tf.Graph().as_default():
        tf.ones(shape=in_shape, dtype='float32')
        compare_tf_with_tvm(in_shape, [], 'ones:0', opt_level=1)

1543

1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
def _test_fill_from_tensor(in_shape):
    """ Use the fill op to create a tensor of ones with non-constant shape.
        Some extra ops need to be added here to prevent the graph from
        being fully constant and folded away."""

    data = np.random.uniform(size=in_shape).astype('float32')

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(
            shape=[in_shape[0], in_shape[1], None, None], dtype=data.dtype)

        x = tf.ones(shape=2*tf.shape(in_data), dtype=data.dtype)
        y = tf.math.add(in_data, tf.reduce_mean(x), name='out1')
        compare_tf_with_tvm(data, 'Placeholder:0', 'out1:0')

1559

1560 1561 1562 1563 1564 1565
def test_forward_fill():
    """ Resize Bilinear """

    _test_fill((32))
    _test_fill((6, 32, 64, 64))
    _test_fill_from_tensor((6, 32, 64, 64))
1566

1567 1568 1569 1570
#######################################################################
# Crop to bounding box
# --------------------

1571

1572 1573 1574 1575 1576 1577
def _test_crop(in_shape, off_h, off_w, tar_h, tar_w):
    """ Crop to bounding box """
    data = np.random.uniform(size=in_shape).astype('float32')
    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
        tf.image.crop_to_bounding_box(in_data, off_h, off_w, tar_h, tar_w)
1578 1579 1580
        compare_tf_with_tvm(data, 'Placeholder:0',
                            'crop_to_bounding_box/Slice:0')

1581 1582 1583 1584 1585

def test_forward_crop():
    """ Crop to bounding box """
    _test_crop((1, 224, 224, 3), 20, 20, 120, 120)

1586 1587

#######################################################################
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
# CropAndResize
# -------------

def _test_forward_crop_and_resize(img_shape, boxes, box_idx, crop_size, method='bilinear', dtype="float32"):
    image = np.random.uniform(0, 10, size=img_shape).astype(dtype)
    tf.reset_default_graph()
    in_data = tf.placeholder(dtype, image.shape, name="in_data")
    tf.image.crop_and_resize(in_data, boxes=boxes, box_ind=box_idx, crop_size=crop_size,
                             method=method, name="crop_and_resize")
    compare_tf_with_tvm([image], ['in_data:0'], 'crop_and_resize:0')

1599

1600 1601 1602
def test_forward_crop_and_resize():
    """ CropAndResize """
    _test_forward_crop_and_resize([1, 11, 11, 3], [[0, 0, 1, 1]], [0], [5, 5])
1603 1604 1605 1606 1607 1608 1609 1610
    _test_forward_crop_and_resize(
        [1, 11, 11, 3], [[0, 0, .9, .9]], [0], [5, 5])
    _test_forward_crop_and_resize(
        [1, 11, 11, 3], [[.1, .2, 1, 1]], [0], [5, 5])
    _test_forward_crop_and_resize(
        [1, 21, 21, 3], [[.2, .3, .7, .9]], [0], [3, 4])
    _test_forward_crop_and_resize(
        [1, 41, 41, 3], [[0.2, 0.4, 0.8, 0.8]], [0], [3, 3])
1611 1612 1613 1614 1615
    _test_forward_crop_and_resize([10, 11, 11, 3],
                                  [[0, 0, 0.9, 0.9], [0.2, 0.2, 0.8, 0.8]],
                                  [0, 1],
                                  [5, 5])
    _test_forward_crop_and_resize([3, 11, 11, 3],
1616 1617
                                  [[0, 0, 0.9, 0.9], [
                                      0.2, 0.2, 0.8, 0.8], [0, 0, 1, 1]],
1618 1619 1620 1621 1622 1623 1624 1625 1626
                                  [0, 1, 2],
                                  [3, 3])
    _test_forward_crop_and_resize([3, 11, 11, 3],
                                  [[0, 0, 1, 0.8], [0, 0, 0.9, 0.9], [0, 0, 1, 0.8]],
                                  [2, 1, 0],
                                  [3, 3])


#######################################################################
1627 1628 1629 1630 1631 1632 1633 1634 1635
# LSTM
# ----

def _test_lstm_cell(batch_size, num_hidden, num_layers, forget_bias, dtype):
    """ One iteration of a LSTM cell """

    tf.reset_default_graph()
    input_size = num_hidden
    input_data = np.full((batch_size, input_size), 1., dtype=dtype)
1636 1637 1638 1639
    in_state_c = np.full(
        (num_layers, batch_size, num_hidden), 0.1, dtype=dtype)
    in_state_h = np.full(
        (num_layers, batch_size, num_hidden), 0.1, dtype=dtype)
1640 1641 1642 1643

    def _get_tensorflow_output():
        with tf.Session() as sess:
            with variable_scope.variable_scope(
1644
                    "root", initializer=init_ops.constant_initializer(0.5)):
1645 1646
                m0 = array_ops.zeros([batch_size, num_hidden])
                m1 = array_ops.zeros([batch_size, num_hidden])
1647
                x = tf.placeholder(shape=(batch_size, input_size), dtype=dtype)
1648
                g, ((out_m0, out_m1)) = \
1649 1650
                    tf.contrib.rnn.LSTMBlockCell(num_hidden,
                                                 forget_bias=forget_bias)(x, ((m0, m1)))
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
                sess.run([variables.global_variables_initializer()])
                res = sess.run([g, out_m0, out_m1], {
                    x.name: np.array([[1., 1.]]),
                    m0.name: 0.1 * np.ones([batch_size, num_hidden]),
                    m1.name: 0.1 * np.ones([batch_size, num_hidden]),
                })
            graph_def = sess.graph.as_graph_def(add_shapes=True)
            final_graph_def = graph_util.convert_variables_to_constants(
                sess,
                graph_def,
                ['root/lstm_cell/LSTMBlockCell'])
            return final_graph_def, res

    graph_def, tf_out = _get_tensorflow_output()
    tvm_output = run_tvm_graph(graph_def, [input_data, in_state_c, in_state_h],
                               ['root/Placeholder', 'root/lstm_cell/LSTMBlockCell_c',
                                'root/lstm_cell/LSTMBlockCell_h'], num_output=2)
    assert isinstance(tvm_output, list)

    out = tvm_output[0]
    out_state = tvm_output[1]
    out_state_tup = np.split(out_state, indices_or_sections=2, axis=1)
    out_state_c = np.reshape(out_state_tup[0], (batch_size, num_hidden))
    out_state_h = np.reshape(out_state_tup[1], (batch_size, num_hidden))
    tvm_out = [out, out_state_c, out_state_h]
    tvm.testing.assert_allclose(tf_out[0], tvm_out[0], rtol=1e-3, atol=1e-3)

1678

1679 1680
def test_forward_lstm():
    '''test LSTM block cell'''
1681
    _test_lstm_cell(1, 2, 1, 0.5, 'float32')
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694


#######################################################################
# Pack
# ---
def _test_pack(axis, shape, **kwargs):

    a = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)
    b = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)

    with tf.Graph().as_default():
        tf_a = array_ops.placeholder(shape=shape, dtype='float32', name='pl_a')
        tf_b = array_ops.placeholder(shape=shape, dtype='float32', name='pl_b')
1695
        tf_c = tf.stack([tf_a, tf_b], axis=axis, **kwargs)
1696 1697
        assert tf_c.op.op_def.name == 'Pack', "tf.stack() is expected to produce 'Pack' operation"

1698
        compare_tf_with_tvm([a, b], ['pl_a:0', 'pl_b:0'], 'stack:0')
1699

1700

1701
def test_forward_pack():
1702 1703 1704
    for axis in range(-3, 3):
        _test_pack(axis, [3, 2, 1])
    for axis in range(-1, 1):
1705 1706 1707
        _test_pack(axis, [3])
    _test_pack(0, [])

1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719

#######################################################################
# Unpack
# ------
def _test_forward_unpack(in_shape, axis, dtype):
    """test operator Unpack"""
    np_data = np.random.uniform(-100, 100, size=in_shape).astype(dtype)
    tf.reset_default_graph()
    in_data = tf.placeholder(dtype, in_shape, name="in_data")
    tf.unstack(in_data, axis=axis, name="Unpack")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'Unpack:0')

1720

1721 1722 1723 1724 1725 1726 1727 1728
def test_forward_unpack():
    _test_forward_unpack((3,), 0, 'int32')
    _test_forward_unpack((3,), -1, 'int16')
    _test_forward_unpack((21, 23, 3), 2, 'float32')

#######################################################################
# Range
# -----
1729 1730


1731 1732 1733 1734 1735 1736
def test_forward_range():
    """test operator Range"""
    tf.reset_default_graph()
    tf.range(1, 18, 3, name="range")
    compare_tf_with_tvm([], [], 'range:0')

1737 1738 1739 1740 1741
    """test type assignment for operator Range"""
    tf.reset_default_graph()
    tf.range(1, 256 + 1, 1, dtype=tf.float32)
    compare_tf_with_tvm([], [], 'range:0')

1742 1743 1744
#######################################################################
# Pad
# ---
1745 1746


1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
def _test_pad(input_shape, paddings, mode, **kwargs):
    """ One iteration of pad operation with given shape"""

    x = np.arange(np.prod(input_shape), dtype=np.float32).reshape(input_shape)

    with tf.Graph().as_default():
        in_data = array_ops.placeholder(shape=input_shape, dtype='float32')
        pad_values = constant_op.constant(paddings)
        pad = tf.pad(in_data, paddings=pad_values, mode=mode, **kwargs)

        if mode == 'CONSTANT':
            if 'constant_values' in kwargs:
                out_name = 'PadV2:0'
            else:
                out_name = 'Pad:0'
1762 1763
        else:
            out_name = 'MirrorPad:0'
1764 1765 1766

        compare_tf_with_tvm(x, 'Placeholder:0', out_name)

1767

1768 1769
def test_forward_pad():
    """ Pad """
1770 1771
    _test_pad((2, 3), [[1, 1], [2, 2]], mode="CONSTANT")
    _test_pad((2, 3), [[1, 1], [2, 2]], mode="CONSTANT", constant_values=1.0)
1772 1773
    _test_pad((2, 3), [[1, 1], [2, 2]], mode="SYMMETRIC")
    _test_pad((2, 3), [[1, 1], [2, 2]], mode="REFLECT")
1774

1775 1776 1777
#######################################################################
# Logical operators
# --------------------
1778 1779


1780 1781 1782 1783 1784
def test_logical_and():
    with tf.Graph().as_default():
        in1 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in1')
        in2 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in2')
        out = tf.logical_and(in1, in2, name='out')
1785 1786 1787 1788
        in_data1 = np.random.choice(
            a=[False, True], size=(1, 4, 4, 3)).astype('bool')
        in_data2 = np.random.choice(
            a=[False, True], size=(1, 4, 4, 3)).astype('bool')
1789 1790
        compare_tf_with_tvm([in_data1, in_data2], ['in1:0', 'in2:0'], 'out:0')

1791

1792 1793 1794 1795 1796
def test_logical_or():
    with tf.Graph().as_default():
        in1 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in1')
        in2 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in2')
        out = tf.logical_or(in1, in2, name='out')
1797 1798 1799 1800
        in_data1 = np.random.choice(
            a=[False, True], size=(1, 4, 4, 3)).astype('bool')
        in_data2 = np.random.choice(
            a=[False, True], size=(1, 4, 4, 3)).astype('bool')
1801 1802
        compare_tf_with_tvm([in_data1, in_data2], ['in1:0', 'in2:0'], 'out:0')

1803

1804 1805 1806 1807 1808
def test_logical_xor():
    with tf.Graph().as_default():
        in1 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in1')
        in2 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in2')
        out = tf.logical_xor(in1, in2, name='out')
1809 1810 1811 1812
        in_data1 = np.random.choice(
            a=[False, True], size=(1, 4, 4, 3)).astype('bool')
        in_data2 = np.random.choice(
            a=[False, True], size=(1, 4, 4, 3)).astype('bool')
1813 1814
        compare_tf_with_tvm([in_data1, in_data2], ['in1:0', 'in2:0'], 'out:0')

1815

1816 1817 1818 1819
def test_logical_not():
    with tf.Graph().as_default():
        in1 = tf.placeholder(tf.bool, shape=[1, 4, 4, 3], name='in1')
        out = tf.logical_not(in1, name='out')
1820 1821
        in_data1 = np.random.choice(
            a=[False, True], size=(1, 4, 4, 3)).astype('bool')
1822 1823
        compare_tf_with_tvm(in_data1, 'in1:0', 'out:0')

1824

1825 1826 1827 1828 1829 1830
def test_forward_logical():
    test_logical_and()
    test_logical_or()
    test_logical_xor()
    test_logical_not()

1831 1832

#######################################################################
1833 1834
# Where, Select
# -------------
1835
def test_forward_where():
1836 1837 1838
    ''' Where: return elements depending on conditions'''
    with tf.Graph().as_default():
        with tf.Session() as sess:
1839 1840 1841 1842
            input1 = tf.placeholder(
                tf.int32, shape=[1, 4, 4, 3], name='input1')
            input2 = tf.placeholder(
                tf.int32, shape=[1, 4, 4, 3], name='input2')
1843 1844
            mask = input1 > input2
            tf.where(mask, input1 + 1, input2 * 2)
1845 1846 1847 1848 1849 1850
            in_data1 = np.random.uniform(
                0, 10, size=(1, 4, 4, 3)).astype("uint32")
            in_data2 = np.random.uniform(
                0, 10, size=(1, 4, 4, 3)).astype("uint32")
            compare_tf_with_tvm([in_data1, in_data2], [
                                'input1:0', 'input2:0'], 'Select:0')
1851 1852 1853


#######################################################################
1854 1855 1856 1857 1858
# Inception V3
# ------------
def test_forward_inception_v3():
    '''test inception V3 model'''
    with tf.Graph().as_default():
1859 1860
        graph_def = tf_testing.get_workload(
            'InceptionV3/inception_v3_2016_08_28_frozen-with_shapes.pb')
1861 1862 1863 1864 1865 1866
        # Call the utility to import the graph definition into default graph.
        graph_def = tf_testing.ProcessGraphDefParam(graph_def)

        data = np.random.uniform(size=(1, 299, 299, 3)).astype('float32')

        with tf.Session() as sess:
1867 1868
            tf_output = run_tf_graph(
                sess, data, 'input:0', 'InceptionV3/Predictions/Reshape_1:0')
1869
            tvm_output = run_tvm_graph(graph_def, data, 'input')
1870 1871
            tvm.testing.assert_allclose(
                tf_output[0], tvm_output[0], rtol=1e-5, atol=1e-5)
1872 1873 1874 1875

#######################################################################
# Inception V1
# ------------
1876 1877


1878 1879 1880
def test_forward_inception_v1():
    '''test inception V1 model'''
    with tf.Graph().as_default():
1881 1882
        graph_def = tf_testing.get_workload(
            "InceptionV1/classify_image_graph_def-with_shapes.pb")
1883 1884 1885 1886 1887 1888 1889 1890
        # Call the utility to import the graph definition into default graph.
        graph_def = tf_testing.ProcessGraphDefParam(graph_def)

        # Build an image from random data.
        from PIL import Image
        from tvm.contrib import util

        img_array = np.random.uniform(size=(1, 600, 600, 3)).astype("uint8")
1891 1892
        img = Image.frombuffer(
            'RGB', (600, 600), img_array.tostring(), 'raw', 'RGB', 0, 1)
1893 1894
        temp = util.tempdir()
        img_path = temp.relpath("tf-test.jpg")
1895
        img.save(img_path)
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905

        import os.path
        if not tf.gfile.Exists(os.path.join(img_path)):
            tf.logging.fatal('File does not exist %s', img_path)
        data = tf.gfile.FastGFile(os.path.join(img_path), 'rb').read()

        temp.remove()

        # Extract tensorflow decoded image frame for tvm input
        with tf.Session() as sess:
1906 1907
            tvm_data = run_tf_graph(
                sess, data, 'DecodeJpeg/contents:0', 'DecodeJpeg:0')
1908 1909

        with tf.Session() as sess:
1910 1911 1912 1913 1914 1915
            tf_output = run_tf_graph(
                sess, data, 'DecodeJpeg/contents:0', 'softmax:0')
            tvm_output = run_tvm_graph(
                graph_def, tvm_data, 'DecodeJpeg/contents')
            tvm.testing.assert_allclose(
                tf_output[0], tvm_output[0], rtol=1e-5, atol=1e-5)
1916 1917 1918 1919

#######################################################################
# Mobilenet
# ---------
1920 1921


1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
def test_forward_mobilenet():
    '''test mobilenet model'''
    # MobilenetV2
    with tf.Graph().as_default():
        graph_def = tf_testing.get_workload(
            "https://storage.googleapis.com/mobilenet_v2/checkpoints/mobilenet_v2_1.4_224.tgz",
            "mobilenet_v2_1.4_224_frozen.pb")
        # Call the utility to import the graph definition into default graph.
        graph_def = tf_testing.ProcessGraphDefParam(graph_def)

        data = np.random.uniform(size=(1, 224, 224, 3)).astype('float32')
        out_node = 'MobilenetV2/Predictions/Reshape_1'

        with tf.Session() as sess:
            # Add shapes to the graph.
            graph_def = tf_testing.AddShapesToGraphDef(sess, out_node)
            tf_output = run_tf_graph(sess, data, 'input:0', out_node + ':0')
            tvm_output = run_tvm_graph(graph_def, data, 'input')
1940 1941
            tvm.testing.assert_allclose(np.squeeze(tvm_output[0]), np.squeeze(tf_output[0]),
                                        rtol=1e-5, atol=1e-5)
1942 1943 1944

#######################################################################
# ResnetV2
1945
# --------
1946 1947


1948 1949 1950 1951
def test_forward_resnetv2():
    '''test resnet model'''
    if is_gpu_available():
        with tf.Graph().as_default():
1952 1953
            graph_def = tf_testing.get_workload(
                "ResnetV2/resnet-20180601_resnet_v2_imagenet-shapes.pb")
1954 1955 1956 1957 1958 1959 1960
            # Call the utility to import the graph definition into default graph.
            graph_def = tf_testing.ProcessGraphDefParam(graph_def)

            data = np.random.uniform(size=(128, 224, 224, 3)).astype('float32')
            out_node = 'ArgMax'

            with tf.Session() as sess:
1961 1962
                tf_output = run_tf_graph(
                    sess, data, 'input_tensor:0', out_node + ':0')
1963 1964 1965 1966 1967
                for device in ["llvm", "cuda"]:
                    ctx = tvm.context(device, 0)
                    if not ctx.exist:
                        print("Skip because %s is not enabled" % device)
                        continue
1968 1969 1970 1971
                    tvm_output = run_tvm_graph(graph_def, data, 'input_tensor', len(tf_output),
                                               target=device)
                    tvm.testing.assert_allclose(np.squeeze(tvm_output[0]), np.squeeze(tf_output[0]),
                                                rtol=1e-5, atol=1e-5)
1972 1973

#######################################################################
1974 1975
# Placeholder
# -----------
1976 1977


1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
def test_forward_placeholder():
    '''test a simple pb with Placeholder node in the end of GraphDef'''
    with tf.Graph().as_default():
        graph_def = tf_testing.get_workload("Custom/placeholder.pb")
        # Call the utility to import the graph definition into default graph.
        graph_def = tf_testing.ProcessGraphDefParam(graph_def)

        data = np.random.uniform(size=(1, 224, 224, 3)).astype('float32')
        out_node = 'mul'

        with tf.Session() as sess:
            # Add shapes to the graph.
            graph_def = tf_testing.AddShapesToGraphDef(sess, out_node)
1991 1992
            tf_output = run_tf_graph(
                sess, data, 'Placeholder:0', out_node + ':0')
1993
            tvm_output = run_tvm_graph(graph_def, data, 'Placeholder')
1994 1995
            tvm.testing.assert_allclose(np.squeeze(tvm_output[0]), np.squeeze(tf_output[0]),
                                        rtol=1e-5, atol=1e-5)
1996

1997

1998
#######################################################################
1999 2000 2001
# PTB
# ---
dir(tf.contrib)
2002 2003


2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
def test_forward_ptb():
    '''test ptb model'''
    config = tf_testing.get_config()
    num_steps = config.num_steps
    num_hidden = config.hidden_size
    num_layers = config.num_layers
    batch_size = config.batch_size
    vocab_size = config.vocab_size
    out_sample_shape = (batch_size, vocab_size)
    out_state_shape = (num_layers, 2, batch_size, num_hidden)
2014
    # Sample input
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
    inpt = "we have no useful information on"
    cnt_sample = 20

    def _pretty_print(items, is_char_model, id2word):
        if not is_char_model:
            return ' '.join([id2word[x] for x in items])
        else:
            return ''.join([id2word[x] for x in items]).replace('_', ' ')

    def _get_tvm_graph_module(graph_def):
2025
        # Cell inputs 'c and 'h' consist of all layers values
2026
        shape_dict = {'Model/Placeholder': (batch_size, num_steps),
2027 2028 2029 2030
                      'Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_c':
                      (num_layers, batch_size, num_hidden),
                      'Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_h':
                      (num_layers, batch_size, num_hidden)}
2031

2032 2033
        mod, params = relay.frontend.from_tensorflow(
            graph_def, shape=shape_dict)
2034 2035

        dtype_dict = {'Model/Placeholder': 'int32',
2036 2037
                      'Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_c': 'float32',
                      'Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_h': 'float32'}
2038 2039
        target = 'llvm'
        with relay.build_config(opt_level=0):
2040
            graph, lib, params = relay.build(mod,
2041 2042
                                             target,
                                             params=params)
2043 2044 2045 2046 2047 2048 2049 2050 2051
        from tvm.contrib import graph_runtime
        ctx = tvm.cpu(0)
        return params, graph_runtime.create(graph, lib, ctx)

    def _do_tvm_sample(model, data, in_states, params, num_samples):
        """Sampled from the model"""
        samples = []
        state = in_states
        sample = None
2052

2053 2054 2055
        def _get_sample(data, state):
            input_data = np.full((batch_size, num_steps), data, dtype="int32")
            in_state_tup = np.split(state, indices_or_sections=2, axis=1)
2056 2057 2058 2059
            in_state_c = np.reshape(
                in_state_tup[0], (num_layers, batch_size, num_hidden))
            in_state_h = np.reshape(
                in_state_tup[1], (num_layers, batch_size, num_hidden))
2060

2061 2062
            model.set_input('Model/Placeholder',
                            tvm.nd.array(input_data.astype("int32")))
2063
            model.set_input('Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_c',
2064
                            tvm.nd.array(in_state_c.astype("float32")))
2065
            model.set_input('Model/RNN/RNN/multi_rnn_cell/cell_0/lstm_cell/LSTMBlockCell_h',
2066
                            tvm.nd.array(in_state_h.astype("float32")))
2067 2068 2069
            model.set_input(**params)
            model.run()
            tvm_output = model.get_output(0, tvm.nd.empty(out_sample_shape,
2070
                                                          "float32")).asnumpy()
2071
            state_output = model.get_output(1, tvm.nd.empty(out_state_shape,
2072
                                                            "float32")).asnumpy()
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
            sample = tf_testing.pick_from_weight(tvm_output[0])

            return sample, state_output

        for x in data:
            sample, state = _get_sample(x, state)

        if sample is not None:
            samples.append(sample)
        else:
            samples.append(0)

        k = 1
        while k < num_samples:
            sample, state = _get_sample(samples[-1], state)
            samples.append(sample)
            k += 1
        return samples, state

    with tf.Graph().as_default():
        word_to_id, id_to_word, graph_def = tf_testing.get_workload_ptb()
        vocab_size = len(word_to_id)
        # Call the utility to import the graph definition into default graph.
        graph_def = tf_testing.ProcessGraphDefParam(graph_def)
        sess = tf.Session()

2099
    # TVM graph module creation
2100 2101 2102 2103 2104 2105
    params, m = _get_tvm_graph_module(graph_def)

    # Create 10 predicted statments of 20 words
    cnt_stm = 0
    while cnt_stm < 10:
        cnt_stm += 1
2106 2107
        in_state = np.full(
            (num_layers, 2, batch_size, num_hidden), 0, dtype="float32")
2108
        seed_for_sample = inpt.split()
2109
        tvm_samples, tvm_state = _do_tvm_sample(m, [word_to_id[word]
2110 2111 2112
                                                    for word in seed_for_sample],
                                                in_state, params, cnt_sample)
        tvm_sample_str = _pretty_print(tvm_samples, False, id_to_word)
2113 2114 2115 2116
        tf_samples, tf_state = tf_testing.do_tf_sample(
            sess,
            [word_to_id[word] for word in seed_for_sample],
            in_state, cnt_sample)
2117 2118
        tf_sample_str = _pretty_print(tf_samples, False, id_to_word)
        inpt = tvm_sample_str
2119 2120
        tvm.testing.assert_allclose(
            tf_samples, tvm_samples, rtol=1e-5, atol=1e-5)
2121
        assert tvm_sample_str == tf_sample_str
2122 2123 2124 2125 2126

#######################################################################
# LRN (Local Response Normalization)
# ----------------------------------

2127

2128 2129 2130 2131 2132 2133 2134
def _test_lrn(ishape, size, axis, bias, alpha, beta):
    """ testing local response normalization """
    lrn_depth_radius = size / 2

    inp_array = np.random.uniform(size=ishape).astype(np.float32)

    with tf.Graph().as_default():
2135 2136
        in1 = tf.placeholder(shape=inp_array.shape,
                             dtype=inp_array.dtype, name="lrn0_data")
2137 2138 2139 2140 2141 2142 2143 2144 2145
        nn_ops.local_response_normalization(in1,
                                            name="lrn",
                                            depth_radius=lrn_depth_radius,
                                            bias=bias,
                                            alpha=alpha,
                                            beta=beta)

        compare_tf_with_tvm(inp_array, 'lrn0_data:0', 'lrn:0')

2146

2147 2148 2149 2150 2151 2152 2153
def test_forward_lrn():
    _test_lrn((1, 3, 20, 20), 3, 1, 1.0, 1.0, 0.5)

#######################################################################
# l2_normalize
# ------------

2154

2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
def _test_l2_normalize(ishape, eps, axis):
    """ testing l2 normalize (uses max, sum, square, sqrt frontend operators)"""

    inp_array = np.random.uniform(size=ishape).astype(np.float32)

    with tf.Graph().as_default():
        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
        nn.l2_normalize(in1,
                        axis=axis,
                        epsilon=eps,
                        name=None,
                        dim=None)

        compare_tf_with_tvm(inp_array, 'Placeholder:0', 'l2_normalize:0')

2170

2171 2172 2173 2174 2175 2176
def test_forward_l2_normalize():
    _test_l2_normalize((1, 3, 20, 20), 0.001, (0,))

#######################################################################
# transpose
# ---------
2177 2178


2179 2180 2181 2182
def _test_forward_transpose(ishape, axes=None):
    data = np.random.uniform(size=ishape).astype(np.float32)

    with tf.Graph().as_default():
2183 2184
        in1 = tf.placeholder(
            shape=data.shape, dtype=data.dtype, name="transpose_data")
2185 2186 2187 2188 2189 2190 2191 2192

        if axes is None:
            tf.transpose(in1)
        else:
            tf.transpose(in1, perm=axes)

        compare_tf_with_tvm(data, 'transpose_data:0', 'transpose:0')

2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
def _test_forward_tranapose_axes_input(ishape, axes):
    data = np.random.uniform(size=ishape).astype(np.float32)
    axes_np = np.array(axes).astype(np.int32)

    with tf.Graph().as_default():
        in1 = tf.placeholder(
            shape=data.shape, dtype=data.dtype, name="transpose_data")

        const1 = tf.constant(axes_np, dtype=tf.int32)

        # make axes an input to tf.transpose, but not an input to the graph,
        # so it can be extracted with infer_value_simulated
        axes = tf.reverse(const1, axis=[-1])
        tf.transpose(in1, axes)

        compare_tf_with_tvm([data], ['transpose_data:0'], 'transpose:0')
2209

2210 2211 2212 2213 2214 2215 2216
def test_forward_transpose():
    _test_forward_transpose((2, 3, 4), (1, 2, 0))
    _test_forward_transpose((2, 3, 4))
    _test_forward_transpose((7, 8, 8, 10))
    _test_forward_transpose((2, 3, 4), (1, 2, 0))
    _test_forward_transpose((2, 3, 4), (0, 1, 2))
    _test_forward_transpose((2, 3, 4, 5), (3, 0, 1, 2))
2217 2218
    _test_forward_tranapose_axes_input((2, 3, 4), (1, 2, 0))
    _test_forward_tranapose_axes_input((2, 3, 4, 5), (3, 0, 1, 2))
2219 2220


2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
def _test_forward_slice_operation_input(input_value, begin_value, size_value):
    input_data = np.array(input_value, dtype=np.float32)
    with tf.Graph().as_default():
        input_tensor = tf.placeholder(
            shape=input_data.shape, dtype=input_data.dtype, name="input")
        begin_tensor = tf.expand_dims(begin_value, axis=0)
        size_tensor = tf.expand_dims(size_value, axis=0)
        slice_tensor = tf.slice(input_tensor, begin_tensor, size_tensor, name='slice_output')
        compare_tf_with_tvm([input_data], ['input:0'], 'slice_output:0')


def test_forward_slice():
    _test_forward_slice_operation_input([1, 1], 0, 2)

2235 2236 2237 2238 2239 2240 2241 2242
def test_forward_ceil():
    ishape = (1, 3, 10, 10)
    inp_array = np.random.uniform(size=ishape).astype(np.float32)
    with tf.Graph().as_default():
        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
        tf.ceil(in1)
        compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Ceil:0')

2243

2244 2245 2246 2247 2248 2249 2250 2251
def test_forward_floor():
    ishape = (1, 3, 10, 10)
    inp_array = np.random.uniform(size=ishape).astype(np.float32)
    with tf.Graph().as_default():
        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
        tf.floor(in1)
        compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Floor:0')

2252

2253 2254 2255
def test_forward_relu():
    ishape = (1, 3, 10, 10)
    inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
2256 2257 2258 2259 2260
    for mode in ['graph_runtime', 'vm']:
        with tf.Graph().as_default():
            in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
            tf.nn.relu(in1)
            compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Relu:0', mode=mode)
2261

2262 2263 2264
def test_forward_leaky_relu():
    ishape = (1, 3, 10, 10)
    inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
2265 2266 2267 2268 2269
    for mode in ['graph_runtime', 'vm']:
        with tf.Graph().as_default():
            in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
            tf.nn.leaky_relu(in1, alpha=0.4)
            compare_tf_with_tvm(inp_array, 'Placeholder:0', 'LeakyRelu:0', mode=mode)
2270

2271

2272 2273 2274 2275 2276 2277 2278 2279
def test_forward_elu():
    ishape = (1, 3, 10, 10)
    inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
    with tf.Graph().as_default():
        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
        tf.nn.elu(in1)
        compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Elu:0')

2280

2281 2282 2283 2284 2285 2286 2287 2288
def test_forward_selu():
    ishape = (1, 3, 10, 10)
    inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
    with tf.Graph().as_default():
        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
        tf.nn.selu(in1)
        compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Selu:0')

2289

2290 2291 2292 2293 2294 2295 2296 2297
def test_forward_tanh():
    ishape = (1, 3, 10, 10)
    inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
    with tf.Graph().as_default():
        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
        tf.nn.tanh(in1)
        compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Tanh:0')

2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313

#######################################################################
# Softmax
# -------
def test_forward_softmax():
    """test operator Softmax """
    def check_softmax(in_shape, axis, dtype):
        np_data = np.random.uniform(-100, 100, size=in_shape).astype(dtype)
        tf.reset_default_graph()
        in_data = tf.placeholder(dtype, in_shape, name="in_data")
        tf.nn.softmax(in_data, axis=axis, name="Softmax")
        compare_tf_with_tvm([np_data], ['in_data:0'], 'Softmax:0')
    check_softmax((2, 3, 5), 2, "float32")
    check_softmax((2, 3, 5), -1, "float32")


2314
#######################################################################
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
# Tensor
# ------

def test_forward_round():
    """test Round"""
    np_data = np.random.uniform(-10, 10, size=(5, 7)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (5, 7), name="in_data")
    tf.round(in_data, name="round")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'round:0')

2326

2327 2328 2329 2330 2331 2332 2333 2334
def test_forward_abs():
    """test operator Abs"""
    np_data = np.random.uniform(1, 100, size=(9, 11)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (9, 11), name="in_data")
    tf.math.abs(in_data, name="abs")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'abs:0')

2335

2336 2337 2338 2339 2340 2341 2342
def _test_forward_zeros_like(in_shape, dtype):
    np_data = np.random.uniform(-10, 10, size=in_shape).astype(dtype)
    tf.reset_default_graph()
    in_data = tf.placeholder(dtype, in_shape, name="in_data")
    tf.zeros_like(in_data, name="zeros_like")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'zeros_like:0')

2343

2344 2345 2346 2347 2348 2349 2350 2351
def test_forward_zeros_like():
    if tf.__version__ < LooseVersion('1.2'):
        _test_forward_zeros_like((2, 3), "int32")
        _test_forward_zeros_like((2, 3, 5), "int8")
        _test_forward_zeros_like((2, 3, 5, 7), "uint16")
        _test_forward_zeros_like((2, 3, 11), "float32")
        _test_forward_zeros_like((2, 3, 11), "float64")

2352

2353 2354 2355 2356 2357 2358 2359 2360
def test_forward_erf():
    ishape = (1, 3, 10, 10)
    inp_array = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
    with tf.Graph().as_default():
        in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
        tf.math.erf(in1)
        compare_tf_with_tvm(inp_array, 'Placeholder:0', 'Erf:0')

2361

2362 2363 2364 2365 2366
def test_forward_squared_difference():
    ishape = (1, 3, 10, 14)
    inp_array_a = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
    inp_array_b = np.random.uniform(-5, 5, size=ishape).astype(np.float32)
    with tf.Graph().as_default():
2367 2368 2369 2370
        in1 = tf.placeholder(shape=inp_array_a.shape,
                             dtype=inp_array_a.dtype, name="in1")
        in2 = tf.placeholder(shape=inp_array_b.shape,
                             dtype=inp_array_b.dtype, name="in2")
2371
        out = tf.math.squared_difference(in1, in2)
2372 2373 2374
        compare_tf_with_tvm([inp_array_a, inp_array_b], [
                            in1.name, in2.name], out.name)

2375

2376 2377 2378 2379 2380 2381 2382
def _test_forward_reverse_v2(in_shape, axis, dtype):
    np_data = np.random.uniform(-10, 10, size=in_shape).astype(dtype)
    tf.reset_default_graph()
    in_data = tf.placeholder(dtype, in_shape, name="in_data")
    tf.reverse(in_data, axis=[axis], name="reverse")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'reverse:0')

2383

2384 2385 2386 2387 2388 2389 2390 2391
def test_forward_reverse_v2():
    """test ReverseV2"""
    _test_forward_reverse_v2((2, 3), 0, "int32")
    _test_forward_reverse_v2((2, 3, 5), 2, "float32")
    _test_forward_reverse_v2((2, 3, 5, 7), 1, "float32")
    _test_forward_reverse_v2((2, 3, 5), -1, "float64")
    _test_forward_reverse_v2((2, 3, 5), -3, "float64")

2392

2393 2394 2395 2396 2397 2398 2399 2400
def test_forward_sign():
    """test Sign"""
    np_data = np.random.uniform(-10, 10, size=(5, 7, 11)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (5, 7, 11), name="in_data")
    tf.sign(in_data, name="sign")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'sign:0')

2401

2402 2403 2404 2405 2406 2407 2408 2409
def test_forward_square():
    """test operator Square """
    np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
    tf.square(in_data, name="square")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'square:0')

2410

2411
def test_forward_pow_exp():
2412 2413 2414
    """test Pow and Exp """
    np_in1 = np.random.uniform(-2, 2, size=(5, 7, 11)).astype(np.float32)
    np_in2 = np.random.uniform(-2, 2, size=(5, 7, 11)).astype(np.float32)
2415 2416 2417 2418
    tf.reset_default_graph()
    in1 = tf.placeholder(tf.float32, (5, 7, 11), name="in1")
    in2 = tf.placeholder(tf.float32, (5, 7, 11), name="in2")
    out1 = tf.pow(in1, in2, name="pow")
2419
    out = tf.exp(in1, name='exp')
2420
    compare_tf_with_tvm([np_in1, np_in2], ['in1:0', 'in2:0'], 'pow:0')
2421
    compare_tf_with_tvm([np_in1], ['in1:0'], 'exp:0')
2422

2423

2424
def test_forward_log():
2425
    """test operator Log """
2426 2427 2428 2429 2430 2431
    np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
    tf.log(in_data, name="log")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'log:0')

2432

2433 2434 2435 2436 2437 2438 2439 2440
def test_forward_log1p():
    """test operator Log1p """
    np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
    tf.log1p(in_data, name="log1p")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'log1p:0')

2441

2442 2443 2444 2445 2446 2447 2448 2449
def test_forward_cos():
    """test operator cos """
    np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
    tf.cos(in_data, name="cos")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'cos:0')

2450

2451 2452 2453 2454 2455 2456 2457 2458
def test_forward_sin():
    """test operator sin """
    np_data = np.random.uniform(1, 100, size=(2, 3, 5)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
    tf.sin(in_data, name="sin")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'sin:0')

2459

2460 2461
def test_forward_negative():
    """test tf operator Neg """
2462 2463
    np_data = np.random.uniform(-100, 255,
                                size=(224, 224, 3)).astype(np.float32)
2464 2465 2466 2467 2468
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (224, 224, 3), name="in_data")
    tf.negative(in_data, name="negative")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'negative:0')

2469

2470 2471 2472 2473 2474 2475 2476 2477
def test_forward_log_softmax():
    """test operator LogSoftmax"""
    np_data = np.random.uniform(1, 100, size=(9, 11)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (9, 11), name="in_data")
    tf.math.log_softmax(in_data, name="LogSoftmax")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'LogSoftmax:0')

2478

2479 2480 2481 2482 2483 2484 2485 2486
def test_forward_softplus():
    """test operator Softplus"""
    np_data = np.random.uniform(1, 10, size=(2, 3, 5)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (2, 3, 5), name="in_data")
    tf.nn.softplus(in_data, name="softplus")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'softplus:0')

2487

2488 2489 2490 2491 2492 2493 2494 2495
def test_forward_rsqrt():
    """test Rsqrt """
    np_data = np.random.uniform(1, 100, size=(5, 7, 11)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (5, 7, 11), name="in_data")
    tf.rsqrt(in_data, name="rsqrt")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'rsqrt:0')

2496

2497 2498 2499 2500 2501 2502 2503 2504
def test_forward_sqrt():
    """test Sqrt """
    np_data = np.random.uniform(1, 100, size=(5, 7, 11)).astype(np.float32)
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.float32, (5, 7, 11), name="in_data")
    tf.sqrt(in_data, name="sqrt")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'sqrt:0')

2505

2506 2507 2508 2509 2510 2511 2512 2513
def _test_forward_right_shift(in_shape, dtype):
    """test operator RightShift"""
    lh_data = np.random.randint(1, 3, size=in_shape).astype(dtype)
    rh_data = np.random.randint(1, 8, size=in_shape).astype(dtype)
    tf.reset_default_graph()
    lft_data = tf.placeholder(dtype, in_shape, name="lft_data")
    rgt_data = tf.placeholder(dtype, in_shape, name="rgt_data")
    tf.bitwise.right_shift(lft_data, rgt_data, name="RightShift")
2514 2515 2516
    compare_tf_with_tvm([lh_data, rh_data], [
                        'lft_data:0', 'rgt_data:0'], 'RightShift:0')

2517 2518 2519 2520 2521

def test_forward_right_shift():
    _test_forward_right_shift((7,), 'int32')
    _test_forward_right_shift((3, 11), 'int16')

2522

2523 2524 2525 2526 2527 2528 2529 2530
def _test_forward_left_shift(in_shape, dtype):
    """test operator LeftShift"""
    lh_data = np.random.randint(100, 1000000, size=in_shape).astype(dtype)
    rh_data = np.random.randint(1, 3, size=in_shape).astype(dtype)
    tf.reset_default_graph()
    lft_data = tf.placeholder(dtype, in_shape, name="lft_data")
    rgt_data = tf.placeholder(dtype, in_shape, name="rgt_data")
    tf.bitwise.left_shift(lft_data, rgt_data, name="LeftShift")
2531 2532 2533
    compare_tf_with_tvm([lh_data, rh_data], [
                        'lft_data:0', 'rgt_data:0'], 'LeftShift:0')

2534 2535 2536 2537 2538

def test_forward_left_shift():
    _test_forward_left_shift((10,), 'int32')
    _test_forward_left_shift((224, 224, 3), 'int16')

2539
#######################################################################
2540 2541
# Mean
# ----
2542 2543


2544 2545 2546 2547 2548 2549
def test_forward_mean():
    def check_mean(ishape, **kwargs):
        inp_array = np.random.uniform(size=ishape).astype(np.float32)
        with tf.Graph().as_default():
            in1 = tf.placeholder(shape=inp_array.shape, dtype=inp_array.dtype)
            tf.keras.backend.mean(in1, **kwargs)
2550 2551
            compare_tf_with_tvm(inp_array, 'Placeholder:0',
                                'Mean:0', no_gpu=True)
2552 2553

    check_mean((10, 8, 16, 32))
2554 2555
    check_mean((10, 8, 16, 32), axis=(2, 3))
    check_mean((10, 8, 16, 32), axis=(1, 2), keepdims=True)
2556 2557

#######################################################################
2558 2559
# Size
# ----
2560 2561


2562 2563 2564
def test_forward_size():
    def check_size(ishape):
        np_input = np.random.uniform(size=ishape).astype(np.float32)
2565 2566 2567 2568 2569

        # if all dimensions are constant, TF will optimize away size operator into constant
        tf_input_shape = list(np_input.shape)
        tf_input_shape[0] = None

2570
        with tf.Graph().as_default():
2571 2572
            input = tf.placeholder(shape=tf_input_shape,
                                   dtype=np_input.dtype, name='input')
2573 2574 2575
            tf.size(input, name='size')
            compare_tf_with_tvm([np_input], ['input:0'], 'size:0')

2576 2577
    check_size((10, 8, 16, 32))
    check_size((10,))
2578 2579

#######################################################################
2580
# All, Any, Max, Min
2581
# ------------------
2582

2583
def test_forward_reduce_all():
2584 2585 2586 2587 2588 2589 2590
    """Test the All operator."""
    np_data = np.random.choice([True, False], size=(5, 7, 11))
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.bool, (5, 7, 11), name="in_data")
    tf.reduce_all(in_data, name="all")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'all:0')

2591 2592 2593 2594 2595 2596 2597 2598
def test_forward_reduce_any():
    """Test the Any operator."""
    np_data = np.random.choice([True, False], size=(5, 7, 11))
    tf.reset_default_graph()
    in_data = tf.placeholder(tf.bool, (5, 7, 11), name="in_data")
    tf.reduce_any(in_data, name="any")
    compare_tf_with_tvm([np_data], ['in_data:0'], 'any:0')
    
2599 2600 2601 2602 2603
def test_forward_reduce_max():
    def check_max(ishape, axis, keepdims, dtype):
        tf.reset_default_graph()
        np_data = np.random.uniform(size=ishape).astype(dtype)
        in_data = tf.placeholder(dtype, name="in_data")
2604 2605
        tf.math.reduce_max(in_data, axis=axis,
                           keepdims=keepdims, name="reduce_max")
2606 2607 2608 2609 2610 2611
        compare_tf_with_tvm([np_data], ['in_data:0'], 'reduce_max:0')

    check_max((10, 8, 16, 32), axis=(-1), keepdims=True, dtype="int32")
    check_max((10, 8, 16, 32), axis=(2, 3), keepdims=True, dtype="float32")
    check_max((10, 8, 16, 32), axis=(1, 2), keepdims=True, dtype='float32')

2612

2613 2614 2615 2616 2617
def test_forward_reduce_min():
    def check_min(ishape, axis, keepdims, dtype):
        tf.reset_default_graph()
        np_data = np.random.uniform(size=ishape).astype(dtype)
        in_data = tf.placeholder(dtype, name="in_data")
2618 2619
        tf.math.reduce_min(in_data, axis=axis,
                           keepdims=keepdims, name="reduce_max")
2620 2621 2622 2623 2624 2625
        compare_tf_with_tvm([np_data], ['in_data:0'], 'reduce_max:0')

    check_min((10, 8, 16, 32), axis=(-1), keepdims=True, dtype="int32")
    check_min((10, 8, 16, 32), axis=(2, 3), keepdims=True, dtype="float32")
    check_min((10, 8, 16, 32), axis=(1, 2), keepdims=True, dtype='float32')

2626
#######################################################################
2627 2628
# Relational operators
# --------------------
2629 2630


2631 2632
def _test_forward_rel_op(data, func):
    with tf.Graph().as_default():
2633 2634 2635 2636
        in1 = tf.placeholder(
            shape=data[0].shape, dtype=data[0].dtype, name='in1')
        in2 = tf.placeholder(
            shape=data[1].shape, dtype=data[1].dtype, name='in2')
2637 2638 2639 2640
        op = func(in1, in2, name='op')
        out = tf.cast(op, tf.int32, name='out1')
        compare_tf_with_tvm([data[0], data[1]], ['in1:0', 'in2:0'], 'out1:0')

2641

2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
def test_forward_rel_ops():
    t1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    t2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
    _test_forward_rel_op([t1, t2], math_ops.less)
    _test_forward_rel_op([t1, t2], math_ops.greater)
    _test_forward_rel_op([t1, t2], math_ops.less_equal)
    _test_forward_rel_op([t1, t2], math_ops.greater_equal)
    _test_forward_rel_op([t1, t2], math_ops.equal)
    _test_forward_rel_op([t1, t2], math_ops.not_equal)

2652 2653 2654
#######################################################################
# ExpandDims
# ----------
2655 2656


2657 2658 2659 2660 2661
def _test_forward_expand_dims(data, axis):
    in1 = tf.placeholder(shape=data.shape, dtype=data.dtype, name='in1')
    out = tf.expand_dims(in1, axis)
    compare_tf_with_tvm([data], [in1.name], out.name)

2662

2663 2664 2665 2666 2667 2668 2669
def test_forward_expand_dims():
    _test_forward_expand_dims(np.int32(1), 0)
    _test_forward_expand_dims(np.array([1]), 0)
    _test_forward_expand_dims(np.array([1]), -1)
    _test_forward_expand_dims(np.array([[1], [2]]), 0)
    _test_forward_expand_dims(np.array([[1], [2]]), 1)
    _test_forward_expand_dims(np.array([[1], [2]]), -1)
2670

2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681

#######################################################################
# Prod
# ----
def _test_forward_reduce_prod(shape, axis, keepdims):
    inp_array1 = np.random.uniform(-5, 5, size=shape).astype(np.float32)
    with tf.Graph().as_default():
        in1 = tf.placeholder(shape=inp_array1.shape, dtype=inp_array1.dtype)
        out = tf.math.reduce_prod(in1, axis, keepdims)
        compare_tf_with_tvm(inp_array1, in1.name, out.name)

2682

2683 2684 2685 2686 2687 2688 2689 2690
def test_forward_reduce_prod():
    _test_forward_reduce_prod((5,), 0, False)
    _test_forward_reduce_prod((5, 5), 0, False)
    _test_forward_reduce_prod((5, 5), 1, False)
    _test_forward_reduce_prod((5,), 0, True)
    _test_forward_reduce_prod((5, 5), 0, True)
    _test_forward_reduce_prod((5, 5), 1, True)

2691 2692

#######################################################################
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
# Maximum, Minimum
# ----------------
def test_forward_maximum():
    """test Op Maximum"""
    def check_maximum(lh_shape, rh_shape, dtype):
        tf.reset_default_graph()
        lh_data = np.random.uniform(size=lh_shape).astype(dtype)
        rh_data = np.random.uniform(size=rh_shape).astype(dtype)
        lft_data = tf.placeholder(dtype, name="lft_data")
        rgt_data = tf.placeholder(dtype, name="rgt_data")
        tf.math.maximum(lft_data, rgt_data, name="maximum")
2704 2705
        compare_tf_with_tvm([lh_data, rh_data], [
                            'lft_data:0', 'rgt_data:0'], 'maximum:0')
2706 2707 2708 2709

    check_maximum((10, 8, 16, 32), (1,), dtype="int32")
    check_maximum((10, 8, 16, 32), (10, 8, 16, 32), dtype="float32")

2710

2711 2712 2713 2714 2715 2716 2717 2718 2719
def test_forward_minimum():
    """test Op Minimum"""
    def check_minimum(lh_shape, rh_shape, dtype):
        tf.reset_default_graph()
        lh_data = np.random.uniform(size=lh_shape).astype(dtype)
        rh_data = np.random.uniform(size=rh_shape).astype(dtype)
        lft_data = tf.placeholder(dtype, name="lft_data")
        rgt_data = tf.placeholder(dtype, name="rgt_data")
        tf.math.minimum(lft_data, rgt_data, name="minimum")
2720 2721
        compare_tf_with_tvm([lh_data, rh_data], [
                            'lft_data:0', 'rgt_data:0'], 'minimum:0')
2722 2723 2724 2725 2726 2727

    check_minimum((10, 8, 16, 32), (1,), dtype="int32")
    check_minimum((10, 8, 16, 32), (10, 8, 16, 32), dtype="float32")


#######################################################################
2728 2729 2730 2731 2732 2733 2734 2735 2736
# PlaceholderWithDefault
# ----------------------
def test_placeholder():
    with tf.Graph().as_default():
        in_data1 = np.random.uniform(-5, 5, size=(3, 4, 5)).astype(np.float32)
        var1 = tf.Variable(in_data1, name='in1')
        var2 = array_ops.placeholder_with_default(var1, None, name='place1')

        in_data2 = np.random.uniform(-5, 5, size=(3, 4, 5)).astype(np.float32)
2737 2738
        place1 = array_ops.placeholder(
            shape=in_data1.shape, dtype=in_data1.dtype, name='in2')
2739 2740 2741 2742

        out1 = tf.math.add(var1, var2, name='out1')
        out2 = tf.math.add(out1, place1, name='out2')

2743 2744
        compare_tf_with_tvm([in_data1, in_data2], ['place1:0', 'in2:0'], 'out2:0',
                            init_global_variables=True)
2745

2746 2747 2748
#######################################################################
# OneHot
# ----------------------
2749 2750


2751 2752 2753 2754
def _test_forward_one_hot(indices_shape, depth, on_value, off_value, axis, out_dtype):
    inp_array1 = np.random.randint(0, 5, size=indices_shape)
    with tf.Graph().as_default():
        in1 = tf.placeholder(shape=inp_array1.shape, dtype=inp_array1.dtype)
2755 2756
        out = tf.one_hot(in1, depth, on_value, off_value,
                         axis, dtype=out_dtype)
2757 2758
        compare_tf_with_tvm(inp_array1, in1.name, out.name)

2759

2760 2761 2762 2763 2764 2765 2766 2767
def test_forward_one_hot():
    _test_forward_one_hot((3,), 3, 1, 0, -1, "int32")
    _test_forward_one_hot((3,), 3, 1.0, 0.0, -1, "float32")
    _test_forward_one_hot((2, 2), 5, 2, -2, 0, "int32")
    _test_forward_one_hot((2, 2), 5, 0.5, -0.5, 1, "float32")
    _test_forward_one_hot((3, 2, 4, 5), 6, 1, 0, 1, "int32")
    _test_forward_one_hot((3, 2, 4, 5), 6, 1.0, 0.0, 0, "float32")

2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
#######################################################################
# AddN
# ----------------------


def _test_forward_add_n(inputs):
    tf.reset_default_graph()
    with tf.Graph().as_default():
        temp = []
        for each in inputs:
            temp.append(tf.placeholder(shape=each.shape, dtype=each.dtype))
        output = tf.add_n(temp)
        compare_tf_with_tvm([each for each in inputs], [
                            each.name for each in temp], output.name)


def test_forward_add_n():
    x = np.random.randint(1, 100, size=(3, 3, 3), dtype=np.int32)
    y = np.random.randint(1, 100, size=(3, 3, 3), dtype=np.int32)
    z = np.random.randint(1, 100, size=(3, 3, 3), dtype=np.int32)
    m, n, o = x.astype(np.float32), y.astype(np.float32), z.astype(np.float32)
    in0 = x
    in1 = [x, y]
    in2 = (x, y, z)
    in3 = m
    in4 = [m, n]
    in5 = (m, n, o)
    _test_forward_add_n(in0)
    _test_forward_add_n(in1)
    _test_forward_add_n(in2)
    _test_forward_add_n(in3)
    _test_forward_add_n(in4)
    _test_forward_add_n(in5)

2802

2803 2804 2805 2806 2807
#######################################################################
# Main
# ----
if __name__ == '__main__':
    # Transforms
2808
    test_forward_slice()
2809 2810
    test_forward_transpose()
    test_forward_reshape()
2811
    test_forward_depthtospace()
2812
    test_forward_spacetodepth()
2813 2814
    test_forward_squeeze()
    test_forward_pack()
2815
    test_forward_size()
2816 2817
    test_forward_broadcast_to()
    test_forward_fill()
2818
    test_forward_crop()
2819 2820
    test_forward_resize()
    test_forward_crop_and_resize()
2821
    test_forward_pad()
2822
    test_forward_unpack()
2823
    test_forward_gather()
2824
    test_forward_gather_nd()
2825
    test_forward_stridedslice()
2826 2827
    test_forward_split()
    test_forward_unstack()
2828
    test_forward_tile()
2829
    test_forward_top_k_v2()
2830
    test_forward_clip_by_value()
2831 2832 2833 2834 2835 2836
    test_forward_maximum()
    test_forward_minimum()
    test_forward_range()
    test_forward_right_shift()
    test_forward_left_shift()
    test_forward_truncatemod()
2837
    test_forward_one_hot()
2838 2839 2840 2841 2842 2843 2844 2845 2846

    # Activations
    test_forward_sigmoid()
    test_forward_relu()
    test_forward_leaky_relu()
    test_forward_elu()
    test_forward_selu()
    test_forward_tanh()

2847 2848 2849 2850 2851
    # Tensor
    test_forward_round()
    test_forward_reverse_v2()
    test_forward_pow_exp()
    test_forward_sign()
2852
    test_forward_log()
2853 2854 2855
    test_forward_log1p()
    test_forward_cos()
    test_forward_sin()
2856
    test_forward_negative()
2857
    test_forward_divide()
2858
    test_forward_floordiv()
2859
    test_forward_abs()
2860 2861
    test_forward_softplus()
    test_forward_sqrt()
2862
    test_forward_rsqrt()
2863
    test_forward_expand_dims()
2864 2865 2866 2867 2868
    test_forward_square()
    test_forward_softmax()
    test_forward_log_softmax()
    test_forward_bias_add()
    test_forward_zeros_like()
2869
    test_forward_erf()
2870
    test_forward_squared_difference()
2871
    test_forward_add_n()
2872
    test_forward_floormod()
2873

2874 2875 2876 2877
    # Reductions
    test_forward_argminmax()
    test_forward_reduce()
    test_forward_mean()
2878
    test_forward_reduce_prod()
2879
    test_forward_reduce_all()
2880
    test_forward_reduce_any()
2881
    test_forward_reduce_min()
2882 2883 2884 2885 2886

    # General
    test_forward_multi_input()
    test_forward_multi_output()
    test_forward_variable()
2887
    test_placeholder()
2888 2889 2890 2891

    # NN
    test_forward_convolution()
    test_forward_pooling()
2892
    test_forward_concat_v2()
2893 2894
    test_forward_lrn()
    test_forward_l2_normalize()
2895 2896
    test_forward_space_to_batch_nd()
    test_forward_batch_to_space_nd()
2897 2898 2899 2900 2901 2902

    # End to End
    test_forward_inception_v3()
    test_forward_inception_v1()
    test_forward_mobilenet()
    test_forward_resnetv2()
2903
    test_forward_placeholder()
2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914
    test_forward_ptb()

    # RNN
    test_forward_lstm()

    # Elementwise
    test_forward_ceil()
    test_forward_floor()

    # Relational ops
    test_forward_rel_ops()
2915
    test_forward_logical()
2916
    test_forward_where()
2917
    test_forward_matmul()
2918 2919 2920
    test_forward_batch_matmul()

    # TODO missing tests: rank