test_op_level2.py 53.4 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
""" Support level2 operator test cases.
"""
Zhi committed
19
import numpy as np
20
import tvm
21
from tvm import autotvm
22
from tvm import relay
Zhi committed
23
from tvm.relay import transform
24
from tvm.relay.testing import ctx_list, run_infer_type
25
from tvm.contrib import util
26
import topi.testing
27

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

def test_conv1d_infer_type():
    # symbolic in batch dimension
    n, c, w = tvm.var("n"), 10, 224
    x = relay.var("x", relay.ty.TensorType((n, c, w), "float32"))
    w = relay.var("w")
    y = relay.nn.conv1d(x, w,
                        kernel_size=3,
                        padding=(1, 1),
                        channels=2)
    yy = run_infer_type(y)
    assert yy.checked_type ==  relay.TensorType(
        (n, 2, 224), "float32")
    assert yy.args[1].checked_type == relay.TensorType(
        (2, 10, 3), "float32")

    # infer by shape of w, mixed precision
    n, c, w = tvm.var("n"), 10, 224
    x = relay.var("x", relay.TensorType((n, c, w), "int8"))
    w = relay.var("w", relay.TensorType((2, 10, 3), "int8"))
    y = relay.nn.conv1d(x, w, out_dtype="int32")
    assert "out_dtype=\"int32\"" in y.astext()
    yy = run_infer_type(y)
    assert yy.checked_type ==  relay.TensorType(
        (n, 2, 222), "int32")

    # infer shape in case of different dtypes for input and weight.
    n, c, w = tvm.var("n"), 10, 224
    x = relay.var("x", relay.TensorType((n, c, w), "uint8"))
    w = relay.var("w", relay.TensorType((2, 10, 3), "int8"))
    y = relay.nn.conv1d(x, w, out_dtype="int32")
    assert "out_dtype=\"int32\"" in y.astext()
    yy = run_infer_type(y)
    assert yy.checked_type ==  relay.TensorType(
        (n, 2, 222), "int32")

    # Infer with NWC
    n, c, w = 4, 32, 224
    x = relay.var("x", relay.TensorType((n, w, c), "int8"))
    wt = relay.var("w")
    y = relay.nn.conv1d(x, wt,
                        kernel_size=3,
                        padding=(1, 1),
                        channels=16,
                        data_layout="NWC",
                        out_dtype="int32")
    yy = run_infer_type(y)
    assert yy.checked_type ==  relay.TensorType(
        (n, w, 16), "int32")


def test_conv1d_run():
    def run_test_conv1d(dtype, out_dtype, scale, dshape, kshape,
                        padding=(1, 1),
                        fref=None,
                        dilation=1,
                        except_targets=None,
                        **attrs):
        if except_targets is None:
            except_targets = []

        x = relay.var("x", shape=dshape, dtype=dtype)
        w = relay.var("w", dtype=dtype)
        y = relay.nn.conv1d(x, w,
                            padding=padding,
                            dilation=dilation,
                            **attrs)
        func = relay.Function([x, w], y)
        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)
        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)
        ref_res = topi.testing.conv1d_ncw_python(
            data.astype(out_dtype), kernel.astype(out_dtype), 1, padding, dilation)

        for target, ctx in ctx_list():
            if target in except_targets:
                continue
            intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
            op_res1 = intrp1.evaluate(func)(data, kernel)
            tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)

    # normal conv1d
    dshape = (1, 3, 224)
    kshape = (10, 3, 3)
    run_test_conv1d("float32", "float32", 1, dshape, kshape,
                    padding=(1, 1), channels=10, kernel_size=3)
    # mixed precision
    run_test_conv1d("int8", "int32", 1, dshape, kshape,
                    padding=(1, 1), channels=10, kernel_size=3)
    # dilated conv2d
    dshape = (1, 3, 18)
    kshape = (10, 3, 3)
    run_test_conv1d("float32", "float32", 1, dshape, kshape,
                    padding=(1, 1), channels=10, kernel_size=3, dilation=3)


123 124
def test_conv2d_infer_type():
    # symbolic in batch dimension
125
    n, c, h, w = tvm.size_var("n"), 10, 224, 224
126 127 128 129 130 131
    x = relay.var("x", relay.ty.TensorType((n, c, h, w), "float32"))
    w = relay.var("w")
    y = relay.nn.conv2d(x, w,
                        kernel_size=(3, 3),
                        padding=(1, 1),
                        channels=2)
Zhi committed
132
    yy = run_infer_type(y)
133
    assert yy.checked_type ==  relay.TensorType(
134
        (n, 2, 224, 224), "float32")
135
    assert yy.args[1].checked_type == relay.TensorType(
136 137 138
        (2, 10, 3, 3), "float32")

    # infer by shape of w, mixed precision
139
    n, c, h, w = tvm.size_var("n"), 10, 224, 224
140 141 142 143
    x = relay.var("x", relay.TensorType((n, c, h, w), "int8"))
    w = relay.var("w", relay.TensorType((2, 10, 3, 3), "int8"))
    y = relay.nn.conv2d(x, w, out_dtype="int32")
    assert "out_dtype=\"int32\"" in y.astext()
Zhi committed
144
    yy = run_infer_type(y)
145
    assert yy.checked_type ==  relay.TensorType(
146 147
        (n, 2, 222, 222), "int32")

148
    # infer shape in case of different dtypes for input and weight.
149
    n, c, h, w = tvm.size_var("n"), 10, 224, 224
150 151 152 153 154 155 156 157
    x = relay.var("x", relay.TensorType((n, c, h, w), "uint8"))
    w = relay.var("w", relay.TensorType((2, 10, 3, 3), "int8"))
    y = relay.nn.conv2d(x, w, out_dtype="int32")
    assert "out_dtype=\"int32\"" in y.astext()
    yy = run_infer_type(y)
    assert yy.checked_type ==  relay.TensorType(
        (n, 2, 222, 222), "int32")

158 159
    # Infer with a different layout
    n, c, h, w = 4, 32, 224, 224
160 161 162
    x = relay.var("x", relay.TensorType((n//4, c//4, h, w, 4, 4), "int8"))
    wt = relay.var("w")
    y = relay.nn.conv2d(x, wt,
163 164 165 166
                        kernel_size=(3, 3),
                        padding=(1, 1),
                        channels=16,
                        data_layout="NCHW4n4c",
167
                        kernel_layout="OIHW4o4i",
168
                        out_dtype="int32")
Zhi committed
169
    yy = run_infer_type(y)
170
    assert yy.checked_type ==  relay.TensorType(
171
        (1, 4, 224, 224, 4, 4), "int32")
172
    assert yy.args[1].checked_type == relay.TensorType(
173 174
        (4, 8, 3, 3, 4, 4), "int8")

175 176 177 178 179 180 181 182 183 184
    # Infer with NHWC
    n, c, h, w = 4, 32, 224, 224
    x = relay.var("x", relay.TensorType((n, h, w, c), "int8"))
    wt = relay.var("w")
    y = relay.nn.conv2d(x, wt,
                        kernel_size=(3, 3),
                        padding=(1, 1),
                        channels=16,
                        data_layout="NHWC",
                        out_dtype="int32")
Zhi committed
185
    yy = run_infer_type(y)
186 187 188 189
    assert yy.checked_type ==  relay.TensorType(
        (n, h, w, 16), "int32")


190 191 192 193 194 195
def test_conv2d_run():
    def run_test_conv2d(dtype, out_dtype, scale, dshape, kshape,
                        padding=(1, 1),
                        fref=None,
                        groups=1,
                        dilation=(1, 1),
196
                        except_targets=None,
197
                        **attrs):
198
        if except_targets is None:
199 200
            except_targets = []

201 202
        x = relay.var("x", shape=dshape, dtype=dtype)
        w = relay.var("w", dtype=dtype)
203 204 205 206 207 208 209 210 211 212 213
        y = relay.nn.conv2d(x, w,
                            padding=padding,
                            dilation=dilation,
                            groups=groups,
                            **attrs)
        func = relay.Function([x, w], y)
        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)
        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)
        dkernel = topi.testing.dilate_python(kernel, (1, 1) + dilation)
        if fref is None:
            ref_res = topi.testing.conv2d_nchw_python(
214 215
                data.astype(out_dtype), dkernel.astype(out_dtype), 1, padding,
                groups=groups)
216 217 218
        else:
            ref_res = fref(data.astype(out_dtype), dkernel.astype(out_dtype))

219

220
        for target, ctx in ctx_list():
221 222
            if target in except_targets:
                continue
223 224 225 226
            intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
            op_res1 = intrp1.evaluate(func)(data, kernel)
            tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    def compile_test_conv2d_arm_cpu(dtype, out_dtype, scale, dshape, kshape,
                        padding=(1, 1),
                        groups=1,
                        dilation=(1, 1),
                        **attrs):
        x = relay.var("x", shape=dshape, dtype=dtype)
        w = relay.var("w", dtype=dtype)
        y = relay.nn.conv2d(x, w,
                            padding=padding,
                            dilation=dilation,
                            groups=groups,
                            **attrs)
        func = relay.Function([x, w], y)
        mod = tvm.relay.Module()
        mod["main"] = func

        test_schedule='{"i": ["llvm -device=arm_cpu", "topi_nn_depthwise_conv2d_nchw", \
                        [["TENSOR", [1, 512, 32, 32], "float32"], \
                        ["TENSOR", [512, 1, 3, 3], "float32"], \
                        [1, 1], [1, 1], [1, 1], "float32"], {}, \
                        ["depthwise_conv2d_nchw", [1, 512, 32, 32, "float32"], \
                        [512, 1, 3, 3, "float32"], [1, 1], [1, 1], [1, 1], "float32"], \
                        {"i": 743640, "t": "contrib_spatial_pack", "c": null, \
250
                        "e": [["tile_co", "sp", [32, 16]], ["tile_oh", "sp", [8, 1]], \
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
                        ["tile_ow", "sp", [1, 8]], \
                        ["reorder_0", "re", [0, 1, 2, 3, 4, 5, 8, 6, 7]], \
                        ["reorder_1", "re", [0, 1, 2, 3, 6, 4, 5]], \
                        ["ann_reduce", "an", ["unroll", "none"]], \
                        ["ann_spatial", "an", ["unroll", "unroll", "vec"]], \
                        ["data_pad_inline", "ot", 4], ["data_vec_inline", "ot", 1], \
                        ["conv_inline", "ot", 0]]}], "r": [[0.0002933163], \
                        0, 3.1976189613342285, 1570811630.6058347], "v": 0.1}'
        temp = util.tempdir()
        with open(temp.relpath("temp.log"), "w") as log_file:
            log_file.write(test_schedule)
        with autotvm.apply_history_best(temp.relpath("temp.log")):
            with relay.build_config(opt_level=3):
                print('Compiling...')
                graph_json, mod, params = tvm.relay.build(mod, target="llvm -device=arm_cpu")

267 268 269 270 271 272 273 274
    # depthwise conv2d
    dshape = (1, 32, 18, 18)
    kshape = (32, 1, 3, 3)
    run_test_conv2d("float32", "float32", 1, dshape, kshape,
                    padding=(1, 1), channels=32, groups=32, kernel_size=(3 ,3),
                    fref=lambda x, w: topi.testing.depthwise_conv2d_python_nchw(
                        x, w, (1, 1), "SAME"))

275 276 277 278 279 280 281
    # depthwise conv2d for arm_cpu
    dshape = (1, 512, 32, 32)
    kshape = (512, 1, 3, 3)
    compile_test_conv2d_arm_cpu("float32", "float32", 1, dshape, kshape,
                                padding=(1, 1), channels=512, 
                                groups=512, kernel_size=(3 ,3))

282
    # CUDA is disabled for 'direct' schedule:
283
    # https://github.com/apache/incubator-tvm/pull/3070#issuecomment-486597553
284 285 286 287 288 289 290 291 292 293 294 295 296
    # group conv2d
    dshape = (1, 32, 18, 18)
    kshape = (32, 4, 3, 3)
    run_test_conv2d("float32", "float32", 1, dshape, kshape,
                    padding=(1, 1), channels=32, groups=8, kernel_size=(3 ,3),
                    except_targets=['cuda'])
    # also group conv2d
    dshape = (1, 32, 18, 18)
    kshape = (64, 1, 3, 3)
    run_test_conv2d("float32", "float32", 1, dshape, kshape,
                    padding=(1, 1), channels=64, groups=32, kernel_size=(3 ,3),
                    except_targets=['cuda'])

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
    # normal conv2d
    dshape = (1, 3, 224, 224)
    kshape = (10, 3, 3, 3)
    run_test_conv2d("float32", "float32", 1, dshape, kshape,
                    padding=(1, 1), channels=10, kernel_size=(3 ,3))
    # mixed precision
    run_test_conv2d("int8", "int32", 1, dshape, kshape,
                    padding=(1, 1), channels=10, kernel_size=(3 ,3))
    kshape = (10, 3, 1, 3)
    # mixed precision.
    run_test_conv2d("int8", "int32", 1, dshape, kshape,
                    padding=(0, 1), channels=10, kernel_size=(1 ,3))
    # dilated conv2d
    dshape = (1, 3, 18, 18)
    kshape = (10, 3, 3, 3)
    run_test_conv2d("float32", "float32", 1, dshape, kshape,
                    padding=(1, 1), channels=10, kernel_size=(3 ,3), dilation=(3, 3))

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
def test_conv2d_winograd():
    class WinogradFallback(autotvm.FallbackContext):
        def _query_inside(self, target, workload):
            key = (target, workload)
            if key in self.memory:
                return self.memory[key]
            cfg = autotvm.task.space.FallbackConfigEntity()
            cfg.template_key = 'winograd'
            cfg.is_fallback = False
            cfg['tile_b'] = autotvm.task.space.SplitEntity([-1, 1, 1, 1])
            cfg['tile_y'] = autotvm.task.space.SplitEntity([-1, 1, 1, 1])
            cfg['tile_x'] = autotvm.task.space.SplitEntity([-1, 1, 1, 1])
            cfg['tile_rc'] = autotvm.task.space.SplitEntity([-1, 1])
            cfg['auto_unroll_max_setp'] = autotvm.task.space.OtherOptionEntity(1500)
            cfg['unroll_explicit'] = autotvm.task.space.OtherOptionEntity(1)
            self.memory[key] = cfg
            return cfg

    def run_test_conv2d_cuda(dtype, out_dtype, scale, dshape, kshape,
                             padding=(1, 1),
                             groups=1,
                             dilation=(1, 1),
                             **attrs):

        x = relay.var("x", shape=dshape, dtype=dtype)
        w = relay.var("w", shape=kshape, dtype=dtype)
        y = relay.nn.conv2d(x, w,
                            padding=padding,
                            dilation=dilation,
                            groups=groups,
                            **attrs)
        func = relay.Function([x, w], y)
        mod = relay.Module()
        mod['main'] = func
        mod = relay.transform.InferType()(mod)

        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)
        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)
        ref_res = topi.testing.conv2d_nchw_python(
            data.astype(out_dtype), kernel.astype(out_dtype), 1, padding,
            groups=groups)

        with WinogradFallback(), relay.build_config(opt_level=3):
            for target, ctx in ctx_list():
                if target != 'cuda':
                    continue
                params = {'w': tvm.nd.array(kernel)}
                graph, lib, params = relay.build_module.build(mod, target=target, params=params)
                module = tvm.contrib.graph_runtime.create(graph, lib, ctx)
                module.set_input('x', tvm.nd.array(data))
                module.set_input(**params)
                module.run()
                op_res1 = module.get_output(0)
                tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-3, atol=1e-3)

    # normal winograd: stride 1, padding 1, kernel 3x3
    dshape = (1, 80, 73, 73)
    kshape = (192, 80, 3, 3)
    run_test_conv2d_cuda("float32", "float32", 1, dshape, kshape,
                         padding=(1, 1), channels=192, kernel_size=(3, 3))
    # extended winograd: stride 1, padding N, kernel 3x3
    run_test_conv2d_cuda("float32", "float32", 1, dshape, kshape,
                         padding=(0, 0), channels=192, kernel_size=(3, 3))
    run_test_conv2d_cuda("float32", "float32", 1, dshape, kshape,
                         padding=(2, 2), channels=192, kernel_size=(3, 3))
    # extended winograd: stride 1, padding N, kernel NxN
    kshape = (192, 80, 7, 7)
    run_test_conv2d_cuda("float32", "float32", 1, dshape, kshape,
                         padding=(2, 2), channels=192, kernel_size=(7, 7))

385

386 387
def test_conv3d_infer_type():
    # symbolic in batch dimension
388
    n, c, d, h, w = tvm.size_var("n"), 10, 224, 224, 224
389 390 391 392 393 394 395 396 397 398 399 400 401
    x = relay.var("x", relay.ty.TensorType((n, c, d, h, w), "float32"))
    w = relay.var("w")
    y = relay.nn.conv3d(x, w,
                        kernel_size=(3, 3, 3),
                        padding=(1, 1, 1),
                        channels=2)
    yy = run_infer_type(y)
    assert yy.checked_type ==  relay.TensorType(
        (n, 2, 224, 224, 224), "float32")
    assert yy.args[1].checked_type == relay.TensorType(
        (2, 10, 3, 3, 3), "float32")

    # infer by shape of w, mixed precision
402
    n, c, d, h, w = tvm.size_var("n"), 10, 224, 224, 224
403 404 405 406 407 408 409 410 411
    x = relay.var("x", relay.TensorType((n, c, d, h, w), "int8"))
    w = relay.var("w", relay.TensorType((2, 10, 3, 3, 3), "int8"))
    y = relay.nn.conv3d(x, w, out_dtype="int32")
    assert "out_dtype=\"int32\"" in y.astext()
    yy = run_infer_type(y)
    assert yy.checked_type ==  relay.TensorType(
        (n, 2, 222, 222, 222), "int32")

    # infer shape in case of different dtypes for input and weight.
412
    n, c, d, h, w = tvm.size_var("n"), 10, 224, 224, 224
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    x = relay.var("x", relay.TensorType((n, c, d, h, w), "uint8"))
    w = relay.var("w", relay.TensorType((2, 10, 3, 3, 3), "int8"))
    y = relay.nn.conv3d(x, w, out_dtype="int32")
    assert "out_dtype=\"int32\"" in y.astext()
    yy = run_infer_type(y)
    assert yy.checked_type ==  relay.TensorType(
        (n, 2, 222, 222, 222), "int32")

    # Infer with NDHWC
    n, c, d, h, w = 4, 32, 224, 224, 224
    x = relay.var("x", relay.TensorType((n, d, h, w, c), "int8"))
    wt = relay.var("w")
    y = relay.nn.conv3d(x, wt,
                        kernel_size=(3, 3, 3),
                        padding=(1, 1, 1),
                        channels=16,
                        data_layout="NDHWC",
                        out_dtype="int32")
    yy = run_infer_type(y)
    assert yy.checked_type ==  relay.TensorType(
        (n, d, h, w, 16), "int32")


436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
def test_conv3d_run():
    def run_test_conv3d(dtype, out_dtype, scale, dshape, kshape,
                        padding=(1, 1, 1),
                        fref=None,
                        groups=1,
                        dilation=(1, 1, 1),
                        except_targets=None,
                        **attrs):
        if except_targets is None:
            except_targets = []

        x = relay.var("x", shape=dshape, dtype=dtype)
        w = relay.var("w", dtype=dtype)
        y = relay.nn.conv3d(x, w,
                            padding=padding,
                            dilation=dilation,
                            groups=groups,
                            **attrs)
        func = relay.Function([x, w], y)
        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)
        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)
        dkernel = topi.testing.dilate_python(kernel, (1, 1) + dilation)
        if fref is None:
            ref_res = topi.testing.conv3d_ncdhw_python(
                data.astype(out_dtype), dkernel.astype(out_dtype), 1, padding,
                groups=groups)
        else:
            ref_res = fref(data.astype(out_dtype), dkernel.astype(out_dtype))


        for target, ctx in ctx_list():
            if target in except_targets:
                continue

            intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
            op_res1 = intrp1.evaluate(func)(data, kernel)
            tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)

    # normal conv3d
    dshape = (1, 3, 5, 224, 224)
    kshape = (10, 3, 3, 3, 3)
    run_test_conv3d("float32", "float32", 1, dshape, kshape,
            padding=(1, 1, 1), channels=10, kernel_size=(3, 3 ,3))

480 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
def test_conv3d_ndhwc_run():
    def run_test_conv3d(dtype, out_dtype, scale, dshape, kshape,
                        padding=(1, 1, 1),
                        fref=None,
                        groups=1,
                        dilation=(1, 1, 1),
                        except_targets=None,
                        **attrs):
        if except_targets is None:
            except_targets = []

        x = relay.var("x", shape=dshape, dtype=dtype)
        w = relay.var("w", dtype=dtype)
        y = relay.nn.conv3d(x, w,
                            padding=padding,
                            dilation=dilation,
                            groups=groups,
                            data_layout="NDHWC", kernel_layout="DHWIO",
                            **attrs)
        func = relay.Function([x, w], y)
        data = np.random.uniform(-scale, scale, size=dshape).astype(dtype)
        kernel = np.random.uniform(-scale, scale, size=kshape).astype(dtype)
        dkernel = topi.testing.dilate_python(kernel, (1, 1) + dilation)
        if fref is None:
            ref_res = topi.testing.conv3d_ndhwc_python(
                data.astype(out_dtype), dkernel.astype(out_dtype), 1, padding)
        else:
            ref_res = fref(data.astype(out_dtype), dkernel.astype(out_dtype))


        for target, ctx in ctx_list():
            if target in except_targets:
                continue

            intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
            op_res1 = intrp1.evaluate(func)(data, kernel)
            tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)

    # normal conv3d
    dshape = (1, 5, 224, 224, 6)
    kshape = (3, 3, 3, 6, 10)
    run_test_conv3d("float32", "float32", 1, dshape, kshape,
            padding=(1, 1, 1), channels=10, kernel_size=(3, 3 ,3), except_targets=["cuda"])

524

525 526
def test_conv2d_transpose_infer_type():
    # symbolic in batch dimension
527
    n, c, h, w = tvm.size_var("n"), 10, 10, 12
528 529 530 531 532 533 534
    x = relay.var("x", relay.TensorType((n, c, h, w), "float32"))
    w = relay.var("w", relay.IncompleteType())
    y = relay.nn.conv2d_transpose(x, w,
                                  kernel_size=(3, 3),
                                  padding=(1, 1),
                                  channels=15)
    assert "channels=15" in y.astext()
Zhi committed
535
    yy = run_infer_type(y)
536
    assert yy.checked_type == relay.TensorType(
537
        (n, 15, 10, 12), "float32")
538
    assert yy.args[1].checked_type == relay.TensorType(
539 540 541
        (10, 15, 3, 3), "float32")

    # infer by shape of w, mixed precision
542
    n, h, w, c = tvm.size_var("n"), 10, 10, 12
543
    x = relay.var("x", relay.TensorType((n, h, w, c), "float32"))
544 545 546 547 548
    w = relay.var("w", relay.TensorType((12, 11, 5, 5), "float32"))
    y = relay.nn.conv2d_transpose(x, w,
                                  output_padding=(1, 1),
                                  channels=11,
                                  data_layout="NHWC")
Zhi committed
549
    yy = run_infer_type(y)
550
    assert yy.checked_type == relay.TensorType(
551 552
        (n, 15, 15, 11), "float32")

553

554
def test_conv2d_transpose_nchw_run():
555 556 557 558 559 560 561 562 563 564 565 566
    dshape = (1, 3, 18, 18)
    kshape = (3, 10, 3, 3)
    oshape = (1, 10, 37, 37)
    x = relay.var("x", shape=dshape)
    w = relay.var("w")
    y = relay.nn.conv2d_transpose(x, w,
                                  channels=10, kernel_size=(3,3), strides=(2,2),
                                  padding=(1,1), output_padding=(2, 2))
    func = relay.Function([x, w], y)
    dtype = "float32"
    data = np.random.uniform(size=dshape).astype(dtype)
    kernel = np.random.uniform(size=kshape).astype(dtype)
567 568 569 570 571
    c_np = topi.testing.conv2d_transpose_nchw_python(
        data, kernel, 2, 1)
    d_np = np.zeros(shape=oshape)
    d_np[:,:,0:c_np.shape[2],0:c_np.shape[3]] = c_np
    ref_res = d_np
572 573 574 575 576 577 578

    for target, ctx in ctx_list():
        intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
        op_res1 = intrp1.evaluate(func)(data, kernel)
        tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)


579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
def test_conv2d_transpose_nhwc_run():
    dshape_nhwc = (1, 18, 18, 3)
    kshape_hwoi = (3, 3, 10, 3)
    oshape_nhwc = (1, 37, 37, 10)
    x = relay.var("x", shape=dshape_nhwc)
    w = relay.var("w")
    # kshape and kernel_layout should have swapped IO.
    # kshape is HWOI and kernel_layout is HWIO
    y = relay.nn.conv2d_transpose(x, w,
                                  channels=10, kernel_size=(3, 3), strides=(2, 2),
                                  padding=(1, 1), output_padding=(2, 2),
                                  data_layout="NHWC", kernel_layout="HWIO")
    func = relay.Function([x, w], y)
    dtype = "float32"
    data = np.random.uniform(size=dshape_nhwc).astype(dtype)
    kernel = np.random.uniform(size=kshape_hwoi).astype(dtype)
    # use true kshape layout here - HWOI
596 597 598
    c_np = topi.testing.conv2d_transpose_nhwc_python(data, kernel, 'HWOI', 2, 1)
    d_np = np.zeros(shape=oshape_nhwc)
    d_np[:,0:c_np.shape[1],0:c_np.shape[2],:] = c_np
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613


def test_conv1d_transpose_ncw_run():
    dshape = (1, 3, 18)
    kshape = (3, 10, 3)
    oshape = (1, 10, 37)
    x = relay.var("x", shape=dshape)
    w = relay.var("w")
    y = relay.nn.conv1d_transpose(x, w,
                                  channels=10, kernel_size=(3,), strides=(2,),
                                  padding=(1,), output_padding=(2,))
    func = relay.Function([x, w], y)
    dtype = "float32"
    data = np.random.uniform(size=dshape).astype(dtype)
    kernel = np.random.uniform(size=kshape).astype(dtype)
614 615 616 617 618
    c_np = topi.testing.conv1d_transpose_ncw_python(
        data, kernel, 2, 1)
    d_np = np.zeros(shape=oshape)
    d_np[:,:,0:c_np.shape[2]] = c_np
    ref_res = d_np
619 620 621 622 623 624

    for target, ctx in ctx_list():
        intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
        op_res1 = intrp1.evaluate(func)(data, kernel)
        tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)

625

626
def test_upsampling_infer_type():
627
    n, c , h, w = tvm.size_var("n"), tvm.size_var("c"), tvm.size_var("h"), tvm.size_var("w")
628
    scale = tvm.const(2.0, "float64")
629
    x = relay.var("x", relay.TensorType((n, c, h, w), "float32"))
630
    y = relay.nn.upsampling(x, scale_h=2, scale_w=2, layout="NCHW", method="bilinear")
631
    "method=\"BINLINEAR\"" in y.astext()
Zhi committed
632
    yy = run_infer_type(y)
633 634 635
    assert yy.checked_type == relay.TensorType((n, c, tvm.expr.Cast("int32", tvm.round(h*scale)),
                                                tvm.expr.Cast("int32", tvm.round(w*scale))),
                                                "float32")
636
    n, c = tvm.size_var("n"), tvm.size_var("c")
637
    x = relay.var("x", relay.TensorType((n, c, 100, 200), "float32"))
638
    y = relay.nn.upsampling(x, scale_h=2, scale_w=2, layout="NCHW", method="bilinear")
Zhi committed
639
    yy = run_infer_type(y)
640
    assert yy.checked_type == relay.TensorType((n, c, 200, 400), "float32")
641

642
def test_upsampling3d_infer_type():
643 644
    n, c, d, h, w = tvm.size_var("n"), tvm.size_var("c"),\
                    tvm.size_var("d"), tvm.size_var("h"), tvm.size_var("w")
645 646 647 648 649 650 651 652 653
    scale = tvm.const(2.0, "float64")
    x = relay.var("x", relay.TensorType((n, c, d, h, w), "float32"))
    y = relay.nn.upsampling3d(x, scale_d=2, scale_h=2, scale_w=2, layout="NCDHW", method="trilinear")

    yy = run_infer_type(y)
    assert yy.checked_type == relay.TensorType((n, c, tvm.expr.Cast("int32", tvm.round(d*scale)),
                                                tvm.expr.Cast("int32", tvm.round(h*scale)),
                                                tvm.expr.Cast("int32", tvm.round(w*scale))),
                                                "float32")
654
    n, c = tvm.size_var("n"), tvm.size_var("c")
655 656 657 658
    x = relay.var("x", relay.TensorType((n, c, 100, 100, 200), "float32"))
    y = relay.nn.upsampling3d(x, scale_d=2, scale_h=2, scale_w=2, layout="NCDHW", method="trilinear")
    yy = run_infer_type(y)
    assert yy.checked_type == relay.TensorType((n, c, 200, 200, 400), "float32")
659 660

def _test_pool2d(opfunc, reffunc):
661
    n, c, h, w = tvm.size_var("n"), 10, 224, 224
662 663 664
    x = relay.var("x", relay.TensorType((n, c, h, w), "float32"))
    y = opfunc(x, pool_size=(1, 1))
    assert "pool_size=" in y.astext()
Zhi committed
665
    yy = run_infer_type(y)
666
    assert yy.checked_type == relay.TensorType((n, 10, 224, 224), "float32")
667 668 669 670 671 672 673
    # test execution
    dtype = "float32"
    dshape = (1, 3, 28, 28)
    x = relay.var("x", shape=dshape)
    y = opfunc(x, pool_size=(2, 2), strides=(2, 2), padding=(0, 0))
    func = relay.Function([x], y)
    data = np.random.uniform(size=dshape).astype(dtype)
674
    ref_res = reffunc(data.reshape(1, 3, 14, 2, 14, 2), axis=(3, 5))
675 676 677 678
    for target, ctx in ctx_list():
        intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
        op_res1 = intrp1.evaluate(func)(data)
        tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)
679

680
def _test_pool2d_int(opfunc, reffunc, dtype):
681
    n, c, h, w = tvm.size_var("n"), 10, 224, 224
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
    x = relay.var("x", relay.TensorType((n, c, h, w), dtype))
    y = opfunc(x, pool_size=(1, 1))
    assert "pool_size=" in y.astext()
    yy = run_infer_type(y)
    assert yy.checked_type == relay.TensorType((n, 10, 224, 224), dtype)
    # test execution
    dtype = "int32"
    dshape = (1, 3, 28, 28)
    x = relay.var("x", shape=dshape, dtype=dtype)
    y = opfunc(x, pool_size=(2, 2), strides=(2, 2), padding=(0, 0))
    func = relay.Function([x], y)
    data = np.random.random_integers(low=-128, high=128, size=dshape)
    ref_res = reffunc(data.reshape(1,3,14,2,14,2), axis=(3,5)).astype(dtype)
    for target, ctx in ctx_list():
        intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
        op_res1 = intrp1.evaluate(func)(data)
        tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)
699 700

def _test_global_pool2d(opfunc, reffunc):
701
    n, c, h, w = tvm.size_var("n"), tvm.size_var("c"), 224, 224
702 703
    x = relay.var("x", relay.TensorType((n, h, w, c), "float32"))
    y = opfunc(x, layout="NHWC")
Zhi committed
704
    yy = run_infer_type(y)
705
    assert yy.checked_type == relay.TensorType((n, 1, 1, c), "float32")
706

707
    n, c, h, w = tvm.size_var("n"), tvm.size_var("c"), tvm.size_var("h"), tvm.size_var("w")
708 709
    x = relay.var("x", relay.TensorType((n, c, h, w), "float32"))
    y = opfunc(x)
Zhi committed
710
    yy = run_infer_type(y)
711
    assert yy.checked_type == relay.TensorType((n, c, 1, 1), "float32")
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
    # test execution
    dtype = "float32"
    dshape = (1, 1024, 7, 7)
    x = relay.var("x", shape=dshape)
    y = opfunc(x)
    func = relay.Function([x], y)
    data = np.random.uniform(size=dshape).astype(dtype)
    ref_res = reffunc(data, axis=(2,3), keepdims=True)
    for target, ctx in ctx_list():
        intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
        op_res1 = intrp1.evaluate(func)(data)
        tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)


def test_pool2d():
    _test_pool2d(relay.nn.max_pool2d, np.max)
    _test_pool2d(relay.nn.avg_pool2d, np.mean)
729 730
    _test_pool2d_int(relay.nn.avg_pool2d, np.mean, 'int32')
    _test_pool2d_int(relay.nn.avg_pool2d, np.mean, 'uint16')
731 732 733 734
    _test_global_pool2d(relay.nn.global_max_pool2d, np.max)
    _test_global_pool2d(relay.nn.global_avg_pool2d, np.mean)


735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
def test_pool1d():

    def _test_pool1d(opfunc):
        n, c, w = tvm.var("n"), 10, 224
        x = relay.var("x", relay.TensorType((n, c, w), "float32"))
        y = opfunc(x, pool_size=(1,))
        assert "pool_size=" in y.astext()
        yy = run_infer_type(y)
        assert yy.checked_type == relay.TensorType((n, 10, 224), "float32")
        # test execution
        dtype = "float32"
        dshape = (1, 3, 32)
        x = relay.var("x", shape=dshape)
        pool_type = 'max' if 'max' in str(opfunc) else 'avg'
        y = opfunc(x, pool_size=(2,), strides=(2,), padding=(0, 0))
        func = relay.Function([x], y)
        data = np.random.uniform(size=dshape).astype(dtype)
        ref_res = topi.testing.pool1d_ncw_python(data, (2,), (2,),
                                                 (0, 0), (1, 3, 16), pool_type, False)
        for target, ctx in ctx_list():
            intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
            op_res1 = intrp1.evaluate(func)(data)
            tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)

    _test_pool1d(relay.nn.max_pool1d)
    _test_pool1d(relay.nn.avg_pool1d)


763 764
def test_pool3d():

765
    def _test_pool3d(opfunc, padding=(0, 0, 0, 0, 0, 0), out_shape=(1, 3, 16, 16, 16)):
766
        n, c, d, h, w = tvm.size_var("n"), 10, 5, 224, 224
767 768 769 770 771 772 773 774 775 776
        x = relay.var("x", relay.TensorType((n, c, d, h, w), "float32"))
        y = opfunc(x, pool_size=(1, 1, 1))
        assert "pool_size=" in y.astext()
        yy = run_infer_type(y)
        assert yy.checked_type == relay.TensorType((n, 10, 5, 224, 224), "float32")
        # test execution
        dtype = "float32"
        dshape = (1, 3, 32, 32, 32)
        x = relay.var("x", shape=dshape)
        pool_type = 'max' if 'max' in str(opfunc) else 'avg'
777
        y = opfunc(x, pool_size=(2, 2, 2), strides=(2, 2, 2), padding=padding)
778
        func = relay.Function([x], y)
779 780 781 782
        # check output shape
        f_out_shape = tuple(map(lambda x: int(x), run_infer_type(func).ret_type.shape))
        assert out_shape == f_out_shape, \
            "Output shape mismatch. expected {}, actual {}".format(out_shape, f_out_shape)
783 784
        data = np.random.uniform(size=dshape).astype(dtype)
        ref_res = topi.testing.pool3d_ncdhw_python(data, (2, 2, 2), (2, 2, 2),
785
                                                   padding, out_shape, pool_type, False)
786 787 788 789 790 791
        for target, ctx in ctx_list():
            intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
            op_res1 = intrp1.evaluate(func)(data)
            tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)

    _test_pool3d(relay.nn.max_pool3d)
792 793 794
    _test_pool3d(relay.nn.max_pool3d, padding=(2, 0, 0, 2, 0, 0), out_shape=(1, 3, 18, 16, 16))
    _test_pool3d(relay.nn.max_pool3d, padding=(0, 3, 0, 0, 3, 0), out_shape=(1, 3, 16, 19, 16))
    _test_pool3d(relay.nn.max_pool3d, padding=(0, 0, 4, 0, 0, 4), out_shape=(1, 3, 16, 16, 20))
795
    _test_pool3d(relay.nn.avg_pool3d)
796 797 798
    _test_pool3d(relay.nn.avg_pool3d, padding=(2, 0, 0, 2, 0, 0), out_shape=(1, 3, 18, 16, 16))
    _test_pool3d(relay.nn.avg_pool3d, padding=(0, 3, 0, 0, 3, 0), out_shape=(1, 3, 16, 19, 16))
    _test_pool3d(relay.nn.avg_pool3d, padding=(0, 0, 4, 0, 0, 4), out_shape=(1, 3, 16, 16, 20))
799 800


801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
def test_avg_pool2d_no_count_pad():
    kh, kw = (4, 4)
    sh, sw = (2, 2)
    ph, pw = (2, 2)
    n = 1
    (ic, ih, iw) = (3, 28, 28)
    (oc, oh, ow) = (3, 15, 15)
    dshape = (n, ic, ih, iw)
    x = relay.var("x", shape=dshape)
    y = relay.nn.avg_pool2d(x,
                            pool_size=(kh, kw),
                            strides=(sw, sw),
                            padding=(ph, pw),
                            count_include_pad=False)
    func = relay.Function([x], y)
    dtype = "float32"
    a_np = np.random.uniform(low=0.001, size=(n, ic, ih, iw)).astype(dtype)
    pad_np = np.zeros(shape=(n, ic, ih+2*ph, iw+2*pw)).astype(dtype)
    no_zero = (range(n), range(ic), (range(ph, ih+ph)), (range(pw, iw+pw)))
    pad_np[np.ix_(*no_zero)] = a_np
    b_np = np.zeros(shape=(n, oc, oh, ow)).astype(dtype)
    for i in range(oh):
        for j in range(ow):
            pad_count = np.sum(pad_np[:, :, i*sh:i*sh+kh, j*sw:j*sw+kw] > 0, axis=(2,3))
            b_np[:,:,i,j] = np.sum(pad_np[:, :, i*sh:i*sh+kh, j*sw:j*sw+kw],
                                   axis=(2,3)) / np.maximum(pad_count, 1)
    ref_res = np.maximum(b_np, 0.0)
    data = a_np

    for target, ctx in ctx_list():
        intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
        op_res1 = intrp1.evaluate(func)(data)
        tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)
834 835

def test_flatten_infer_type():
836
    d1, d2, d3, d4 = tvm.size_var("d1"), tvm.size_var("d2"), tvm.size_var("d3"), tvm.size_var("d4")
837 838
    x = relay.var("x", relay.TensorType((d1, d2, d3, d4), "float32"))
    y = relay.nn.batch_flatten(x)
Zhi committed
839
    yy = run_infer_type(y)
840
    assert yy.checked_type == relay.TensorType((d1, ((d2*d3)*d4)), "float32")
841

842 843
    x = relay.var("x", relay.TensorType((3, 2, 4, 3), "float32"))
    y = relay.nn.batch_flatten(x)
Zhi committed
844
    yy = run_infer_type(y)
845
    assert yy.checked_type == relay.TensorType((3, 24), "float32")
846

847 848
    x = relay.var("x", relay.TensorType((d1, 2, d3, 3), "float32"))
    y = relay.nn.batch_flatten(x)
Zhi committed
849
    yy = run_infer_type(y)
850
    assert yy.checked_type == relay.TensorType((d1, ((2*d3)*3)), "float32")
851

852 853 854 855 856
    shape = (1, 5, 10, 10)
    o_shape = (1, 500)
    dtype = "float32"
    x = relay.var("x", relay.TensorType(shape, dtype))
    z = relay.nn.batch_flatten(x)
Zhi committed
857
    yy = run_infer_type(z)
858 859 860 861 862 863 864 865 866 867 868 869 870
    assert yy.checked_type == relay.TensorType(o_shape, dtype)
    func = relay.Function([x], z)
    x_data = np.random.uniform(low=-1, high=1, size=shape).astype(dtype)
    ref_res = x_data.flatten().reshape(o_shape)

    for target, ctx in ctx_list():
        intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
        intrp2 = relay.create_executor("debug", ctx=ctx, target=target)
        op_res1 = intrp1.evaluate(func)(x_data)
        tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5)
        op_res2 = intrp2.evaluate(func)(x_data)
        tvm.testing.assert_allclose(op_res2.asnumpy(), ref_res, rtol=1e-5)

871 872 873
def test_pad_infer_type():
    # entirely concrete case
    n, c, h, w = 1, 2, 3, 4
874 875 876
    t = relay.var("t", relay.TensorType((n, c, h, w), "float32"))
    y = relay.nn.pad(t, ((1, 1), (2, 2), (3, 3), (4, 4)))
    "pad_width=" in y.astext()
Zhi committed
877
    yy = run_infer_type(y)
878
    assert yy.checked_type == relay.TensorType((3, 6, 9, 12), "float32")
879 880

    # some symbolic values
881
    n, c, h, w = tvm.size_var("n"), 2, 3, tvm.size_var("w")
882 883
    t = relay.var("t", relay.TensorType((n, c, h, w), "float32"))
    y = relay.nn.pad(t, ((1, 1), (2, 2), (3, 3), (4, 4)))
Zhi committed
884
    yy = run_infer_type(y)
885
    assert yy.checked_type == relay.TensorType((n + 2, 6, 9, w + 8), "float32")
886

887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
def test_pad_run():
    def _test_run(dtype):
        dshape = (4, 10, 7, 7)
        x = relay.var("x", shape=dshape)
        y = relay.nn.pad(x, ((1, 1), (2, 2), (3, 3), (4, 4)))
        func = relay.Function([x], y)
        data = np.random.uniform(size=dshape).astype(dtype)
        ref_res = np.pad(data, ((1, 1), (2, 2), (3, 3), (4, 4)), 'constant')
        for target, ctx in ctx_list():
            intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
            op_res1 = intrp1.evaluate(func)(data)
            tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5, atol=1e-5)

    _test_run('float32')
    _test_run('int32')
902

903
def test_lrn():
904
    n, c , h, w = tvm.size_var("n"), tvm.size_var("c"), tvm.size_var("h"), tvm.size_var("w")
905 906 907
    x = relay.var("x", shape=(n, c , h, w))
    y = relay.nn.lrn(x, size=10, axis=2, bias=0.5, alpha=.00001, beta=0.75)
    "alpha=" in y.astext()
Zhi committed
908
    yy = run_infer_type(y)
909
    assert yy.checked_type == relay.TensorType((n, c , h, w))
910

911 912 913 914 915 916 917 918 919
    shape = (1, 5, 10, 10)
    dtype = "float32"
    x = relay.var("x", relay.TensorType(shape, dtype))
    size=5
    axis=1
    bias=0.5
    alpha=.00001
    beta=0.75
    z = relay.nn.lrn(x, size=size, axis=axis, bias=bias, alpha=alpha, beta=beta)
Zhi committed
920
    yy = run_infer_type(z)
921 922 923 924 925 926 927 928 929 930 931 932 933
    assert yy.checked_type == relay.TensorType(shape, dtype)
    func = relay.Function([x], z)
    x_data = np.random.uniform(low=-1, high=1, size=shape).astype(dtype)
    ref_res = topi.testing.lrn_python(x_data, size, axis, bias, alpha, beta)

    for target, ctx in ctx_list():
        intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
        intrp2 = relay.create_executor("debug", ctx=ctx, target=target)
        op_res1 = intrp1.evaluate(func)(x_data)
        tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5)
        op_res2 = intrp2.evaluate(func)(x_data)
        tvm.testing.assert_allclose(op_res2.asnumpy(), ref_res, rtol=1e-5)

934
def test_l2_normalize():
935
    n, c , h, w = tvm.size_var("n"), tvm.size_var("c"), tvm.size_var("h"), tvm.size_var("w")
936 937 938
    x = relay.var("x", shape=(n, c , h, w))
    y = relay.nn.l2_normalize(x, eps=0.001, axis=[1])
    "axis=" in y.astext()
Zhi committed
939
    yy = run_infer_type(y)
940
    assert yy.checked_type == relay.TensorType((n, c , h, w))
941

942 943 944 945 946 947
    shape = (1, 5, 10, 10)
    dtype = "float32"
    x = relay.var("x", relay.TensorType(shape, dtype))
    eps=0.001
    axis=1
    z = relay.nn.l2_normalize(x, eps=0.001, axis=[axis])
Zhi committed
948
    yy = run_infer_type(z)
949 950 951 952 953 954 955 956 957 958 959 960 961
    assert yy.checked_type == relay.TensorType(shape, dtype)
    func = relay.Function([x], z)
    x_data = np.random.uniform(low=-1, high=1, size=shape).astype(dtype)
    ref_res = topi.testing.l2_normalize_python(x_data, eps, axis)

    for target, ctx in ctx_list():
        intrp1 = relay.create_executor("graph", ctx=ctx, target=target)
        intrp2 = relay.create_executor("debug", ctx=ctx, target=target)
        op_res1 = intrp1.evaluate(func)(x_data)
        tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5)
        op_res2 = intrp2.evaluate(func)(x_data)
        tvm.testing.assert_allclose(op_res2.asnumpy(), ref_res, rtol=1e-5)

962

963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
def batch_flatten(data):
    shape = data.shape
    target_dim = 1
    for i in range(len(shape) - 1):
        target_dim = target_dim * shape[i + 1]
    return np.reshape(data, (shape[0], target_dim))


def test_batch_flatten():
    t1 = relay.TensorType((5, 10, 5))
    x = relay.Var("x", t1)
    func = relay.Function([x], relay.nn.batch_flatten(x))

    data = np.random.rand(5, 10, 5).astype(t1.dtype)
    ref_res = batch_flatten(data)
    for target, ctx in ctx_list():
        intrp = relay.create_executor("graph", ctx=ctx, target=target)
        op_res = intrp.evaluate(func)(data)
        np.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=0.01)


984
def _test_upsampling(layout, method, align_corners=False):
985
    n, c, h, w = tvm.size_var("n"), 16, 32, 32
986 987
    scale_h = 2.0
    scale_w = 2.0
988 989 990
    dtype = "float32"
    def get_shape():
        if layout == "NCHW":
991
            return (c, h, w), (c, int(round(h*scale_h)), int(round(w*scale_w)))
992
        else:
993
            return (h, w, c), (int(round(h*scale_h)), int(round(w*scale_w)), c)
994 995
    ishape, oshape = get_shape()
    x = relay.var("x", relay.TensorType((n,) + ishape, dtype))
996
    y = relay.nn.upsampling(x, scale_h=scale_h, scale_w=scale_w, layout=layout,
997
                            method=method, align_corners=align_corners)
Zhi committed
998
    yy = run_infer_type(y)
999 1000 1001
    assert yy.checked_type == relay.TensorType((n,) + oshape, dtype)
    dshape = (1,) + ishape
    x = relay.var("x", shape=dshape)
1002
    y = relay.nn.upsampling(x, scale_h=scale_h, scale_w=scale_w, layout=layout,
1003
                            method=method, align_corners=align_corners)
1004 1005
    func = relay.Function([x], y)
    data = np.random.uniform(size=dshape).astype(dtype)
1006
    if method == "nearest_neighbor":
1007
        ref = topi.testing.upsampling_python(data, (scale_h, scale_w), layout)
1008
    else:
1009 1010
        ref = topi.testing.bilinear_resize_python(data, (int(round(h*scale_h)),
                                                  int(round(w*scale_w))), layout)
1011 1012 1013 1014 1015 1016 1017
    for target, ctx in ctx_list():
        executor = relay.create_executor("graph", ctx=ctx, target=target)
        out = executor.evaluate(func)(data)
        tvm.testing.assert_allclose(out.asnumpy(), ref, rtol=1e-5, atol=1e-5)


def test_upsampling():
1018 1019 1020 1021
    _test_upsampling("NCHW", "nearest_neighbor")
    _test_upsampling("NCHW", "bilinear", True)
    _test_upsampling("NHWC", "nearest_neighbor")
    _test_upsampling("NHWC", "bilinear", True)
1022

1023
def _test_upsampling3d(layout, method, coordinate_transformation_mode="half_pixel"):
1024
    n, c, d, h, w = tvm.size_var("n"), 8, 16, 16, 16
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    scale_d = 2.0
    scale_h = 2.0
    scale_w = 2.0
    dtype = "float32"
    def get_shape():
        if layout == "NCDHW":
            return (c, d, h, w), (c, int(round(d*scale_d)), int(round(h*scale_h)),\
                                  int(round(w*scale_w)))
        else:
            return (d, h, w, c), (int(round(d*scale_d)), int(round(h*scale_h)),\
                                  int(round(w*scale_w)), c)
    ishape, oshape = get_shape()
    x = relay.var("x", relay.TensorType((n,) + ishape, dtype))
    y = relay.nn.upsampling3d(x, scale_d=scale_d, scale_h=scale_h, scale_w=scale_w,\
                              layout=layout, method=method,\
                              coordinate_transformation_mode=coordinate_transformation_mode)

    yy = run_infer_type(y)
    assert yy.checked_type == relay.TensorType((n,) + oshape, dtype)
    dshape = (1,) + ishape
    x = relay.var("x", shape=dshape)
    y = relay.nn.upsampling3d(x, scale_d=scale_d, scale_h=scale_h, scale_w=scale_w,\
                            layout=layout, method=method,\
                            coordinate_transformation_mode=coordinate_transformation_mode)
    func = relay.Function([x], y)
    data = np.random.uniform(size=dshape).astype(dtype)
    if method == "nearest_neighbor":
        ref = topi.testing.upsampling3d_python(data, (scale_d, scale_h, scale_w), layout)
    else:
        ref = topi.testing.trilinear_resize3d_python(data, (int(round(d*scale_d)),\
                                                     int(round(h*scale_h)),\
                                                     int(round(w*scale_w))), layout)
    for target, ctx in ctx_list():
        executor = relay.create_executor("graph", ctx=ctx, target=target)
        out = executor.evaluate(func)(data)
        tvm.testing.assert_allclose(out.asnumpy(), ref, rtol=1e-5, atol=1e-5)

def test_upsampling3d():
    _test_upsampling3d("NCDHW", "nearest_neighbor")
    _test_upsampling3d("NCDHW", "trilinear", "align_corners")
    _test_upsampling3d("NDHWC", "nearest_neighbor")
    _test_upsampling3d("NDHWC", "trilinear", "align_corners")
1067

1068
def test_conv2d_int8_intrinsics():
1069 1070 1071 1072 1073
    def _compile(ic, oc, target, data_layout, kernel_layout, dtypes):
        input_dtype, weight_dtype, output_dtype = dtypes

        n, h, w, ch, cw = 1, 64, 64, 3, 3
        if data_layout == 'NCHW':
1074 1075
            data_shape = (n, ic, h, w)
            x = relay.var("x", relay.TensorType(data_shape, input_dtype))
1076
        elif data_layout == 'NHWC':
1077 1078
            data_shape = (n, h, w, ic)
            x = relay.var("x", relay.TensorType(data_shape, input_dtype))
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
        else:
            raise ValueError('Not supported')

        if kernel_layout == 'OIHW':
            kernel_shape = (oc, ic, ch, cw)
        elif kernel_layout == 'HWIO':
            kernel_shape = (ch, cw, ic, oc)
        else:
            raise ValueError('Not supported')

1089 1090
        weight = relay.var("weight", relay.TensorType(kernel_shape, weight_dtype))
        y = relay.nn.conv2d(x, weight,
1091 1092 1093 1094
                            kernel_size=(ch, cw),
                            channels=oc,
                            padding=(1, 1),
                            dilation=(1, 1),
1095 1096
                            data_layout=data_layout,
                            kernel_layout=kernel_layout,
1097
                            out_dtype=output_dtype)
1098
        func = relay.Function([x, weight], y)
1099
        wdata = np.random.rand(*kernel_shape) * 10
1100 1101
        parameters = {"weight": tvm.nd.array(wdata.astype(weight_dtype))}

1102 1103
        with relay.build_config(opt_level=3):
            graph, lib, params = relay.build(func, target, params=parameters)
1104

1105 1106 1107
        assembly = lib.get_source("asm")
        return assembly

1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
    def _has_fast_int8_instructions(asm, target):
        if 'skylake-avx512' in target:
            return "pmaddubs" in asm
        elif 'cascadelake' in target:
            return "vpdpbusd" in asm
        else:
            assert False, "Target should be Skylake or Cascadelake"

    # compile conv2d for x86 (skylake, cascadelake) and test assembly contains *pmadd* instructions
    targets = ["llvm -mcpu=skylake-avx512", "llvm -mcpu=cascadelake"]
    llvm_version = tvm.codegen.llvm_version_major()
    for target in targets:
        if llvm_version >= 8:
1121
            dtypes = ('uint8', 'int8', 'int32')
1122 1123 1124
            # Sweep the input channels to check int8 robustness
            # Input channels should be a multiple of 4 internally.
            for ic in [1, 4, 6]:
1125
                asm = _compile(ic=ic, oc=16, target=target, data_layout="NCHW",
1126
                               kernel_layout='OIHW',
1127
                               dtypes=dtypes)
1128 1129 1130
                assert _has_fast_int8_instructions(asm, target)

            for ic in [1, 4, 6]:
1131
                asm = _compile(ic=ic, oc=16, target=target, data_layout="NHWC",
1132
                               kernel_layout='HWIO',
1133
                               dtypes=dtypes)
1134 1135 1136 1137 1138
                assert _has_fast_int8_instructions(asm, target)

            # Sweep the output channels to check int8 robustness
            # Output channels should be a multiple of 16 internally.
            for oc in [4, 16, 20]:
1139
                asm = _compile(ic=8, oc=oc, target=target, data_layout="NCHW",
1140
                               kernel_layout='OIHW',
1141
                               dtypes=dtypes)
1142 1143 1144
                assert _has_fast_int8_instructions(asm, target)

            for oc in [4, 16, 20]:
1145
                asm = _compile(ic=8, oc=oc, target=target, data_layout="NHWC",
1146
                               kernel_layout='HWIO',
1147
                               dtypes=dtypes)
1148 1149 1150 1151
                assert _has_fast_int8_instructions(asm, target)

            # Check that both non-divisible oc and ic work
            asm = _compile(ic=17, oc=29, target=target, data_layout="NCHW", kernel_layout='OIHW',
1152
                           dtypes=dtypes)
1153
            assert _has_fast_int8_instructions(asm, target)
1154

1155
            asm = _compile(ic=17, oc=29, target=target, data_layout="NHWC", kernel_layout='HWIO',
1156
                           dtypes=dtypes)
1157 1158
            assert _has_fast_int8_instructions(asm, target)

1159 1160 1161 1162 1163 1164
    # Check that int8 x int8 goes through legalization so that fast instructions can be picked up.
    for target in targets:
        if llvm_version >= 8:
            dtypes = (('int8', 'int8', 'int32'))
            # Check that both non-divisible oc and ic work
            asm = _compile(ic=17, oc=29, target=target, data_layout="NCHW", kernel_layout='OIHW',
1165
                           dtypes=dtypes)
1166
            assert _has_fast_int8_instructions(asm, target)
1167

1168
            asm = _compile(ic=17, oc=29, target=target, data_layout="NHWC", kernel_layout='HWIO',
1169
                           dtypes=dtypes)
1170 1171 1172 1173 1174 1175 1176 1177
            assert _has_fast_int8_instructions(asm, target)

    # Ensure that code is generated when datatypes are not HW supported.
    dtypes = ('uint8', 'uint8', 'int32')
    asm = _compile(ic=16, oc=32, target=target, data_layout="NHWC", kernel_layout='HWIO',
                   dtypes=dtypes)
    # Check that intrinisic is not present in the assembly.
    assert not _has_fast_int8_instructions(asm, target)
1178 1179 1180 1181

    # Check that a vectorized instruction is generated for older Intel
    # generations, because we default to NCHWc layout.
    target = "llvm -mcpu=core-avx2"
1182 1183 1184
    fast_int8_dtypes = ('uint8', 'int8', 'int32')
    asm = _compile(ic=16, oc=32, target=target, data_layout="NCHW", kernel_layout='OIHW',
                   dtypes=fast_int8_dtypes)
1185 1186 1187 1188
    # Check that vector int mult and add instructions are generated.
    assert "vpmulld" in asm and "vpadd" in asm


1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
def test_depthwise_conv2d_int8():
    input_dtype = 'uint8'
    weight_dtype = 'int8'
    output_dtype = 'int32'

    data_shape = (1, 64, 56, 56)
    x = relay.var("x", relay.TensorType(data_shape, input_dtype))

    kernel_shape = (64, 1, 3, 3)
    weight = relay.var("weight", relay.TensorType(kernel_shape, weight_dtype))

    y = relay.nn.conv2d(x, weight,
                        kernel_size=(3, 3),
                        groups=64,
                        padding=(1, 1),
                        dilation=(1, 1),
                        out_dtype=output_dtype)
    func = relay.Function([x, weight], y)
    wdata = np.random.rand(*kernel_shape) * 10
    parameters = {"weight": tvm.nd.array(wdata.astype(weight_dtype))}

    targets = ["llvm -mcpu=skylake-avx512", "llvm -mcpu=cascadelake"]
    llvm_version = tvm.codegen.llvm_version_major()
    for target in targets:
        if llvm_version >= 8:
            with relay.build_config(opt_level=3):
                graph, lib, params = relay.build(func, target, params=parameters)


1218 1219
def test_bitserial_conv2d_infer_type():
    # Basic shape test with ambiguous batch.
1220
    n, c, h, w = tvm.size_var("n"), 32, 224, 224
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    x = relay.var("x", relay.ty.TensorType((n, c, h, w), "int16"))
    w = relay.var("w", relay.ty.TensorType((32, 32, 3, 3), "int16"))
    y = relay.nn.bitserial_conv2d(
        x, w, kernel_size=(3, 3), padding=(0, 0), channels=32)
    yy = run_infer_type(y)
    assert yy.checked_type ==  relay.TensorType(
        (n, 32, 222, 222), "int16")


def test_bitpack_infer_type():
    # Test axis packing shape inference.
    o, i, h, w = 32, 32, 128, 128
    x = relay.var("x", relay.ty.TensorType((o, i, h, w), "int16"))
    y = relay.nn.bitpack(x, bit_axis=4, pack_axis=1, pack_type='uint16', bits=1)
    yy = run_infer_type(y)
    assert yy.checked_type ==  relay.TensorType(
        (32, 2, 128, 128, 1), "uint16")


1240
if __name__ == "__main__":
1241
    test_pool1d()
1242
    test_pool2d()
1243
    test_pool3d()
1244
    test_avg_pool2d_no_count_pad()
1245 1246
    test_lrn()
    test_l2_normalize()
1247
    test_conv1d_infer_type()
1248
    test_conv2d_infer_type()
1249
    test_conv3d_infer_type()
1250
    test_bitpack_infer_type()
1251
    test_upsampling_infer_type()
1252
    test_upsampling3d_infer_type()
1253
    test_flatten_infer_type()
1254
    test_pad_infer_type()
1255
    test_pad_run()
1256
    test_conv2d_transpose_infer_type()
1257 1258
    test_conv2d_transpose_nchw_run()
    test_conv2d_transpose_nhwc_run()
1259
    test_conv1d_transpose_ncw_run()
1260
    test_conv1d_run()
1261
    test_conv2d_run()
1262
    test_conv2d_winograd()
1263
    test_conv3d_run()
1264
    test_conv3d_ndhwc_run()
1265
    test_bitserial_conv2d_infer_type()
1266
    test_batch_flatten()
1267
    test_upsampling()
1268
    test_upsampling3d()
1269
    test_conv2d_int8_intrinsics()
1270
    test_depthwise_conv2d_int8()