test_op_level1.py 17.5 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
import numpy as np
18
import pytest
Zhi committed
19
import tvm
20
from tvm import te
21
import scipy
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
import topi.testing
26
from tvm.contrib.nvcc import have_fp16
27

Zhi committed
28

29 30 31 32 33 34 35 36
def sigmoid(x):
    one = np.ones_like(x)
    return one / (one + np.exp(-x))

def relu(x):
    x_copy = np.copy(x)
    np.maximum(x_copy, 0, x_copy)
    return x_copy
37

38 39 40 41
def rsqrt(x):
    one = np.ones_like(x)
    return one / np.sqrt(x)

42
def test_unary_op():
43
    def check_single_op(opfunc, ref, dtype):
44
        shape = (10, 4)
45 46 47
        dtype = dtype
        tp = relay.TensorType(shape)
        x = relay.var("x", tp, dtype=dtype)
48 49
        y = opfunc(x)
        # test printer
50
        assert ("{}(%x)".format(y.op.name)) in y.astext()
51
        # test type inference
Zhi committed
52 53
        yy = run_infer_type(y)
        assert yy.checked_type == tp
54

55 56 57
        if ref is not None:
            data = np.random.rand(*shape).astype(dtype)
            ref_res = ref(data)
58 59 60 61
            func = relay.Function([x], y)
            for target, ctx in ctx_list():
                # use graph by execuor default for testing, as we need
                # create function explicitly to avoid constant-folding.
62 63
                if dtype ==  'float16' and target == 'cuda' and not have_fp16(tvm.gpu(0).compute_version):
                    continue
64 65 66 67
                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)

68 69

    for opfunc, ref in [(tvm.relay.log, np.log),
70
                        (tvm.relay.exp, np.exp),
71
                        (tvm.relay.erf, scipy.special.erf),
72
                        (tvm.relay.sqrt, np.sqrt),
73
                        (tvm.relay.rsqrt, rsqrt),
74 75
                        (tvm.relay.sigmoid, sigmoid),
                        (tvm.relay.tanh, np.tanh),
76 77
                        (relay.nn.relu, relu),
                        (tvm.relay.cos, np.cos),
78
                        (tvm.relay.sin, np.sin),
79
                        (tvm.relay.tan, np.tan),
80
                        (tvm.relay.atan, np.arctan)]:
81 82
        for dtype in ['float16', 'float32']:
            check_single_op(opfunc, ref, dtype)
83

84

85
def test_binary_op():
86 87 88
    def inst(vars, sh):
        return [vars.get(s, s) for s in sh]

89
    def check_binary_op(opfunc, ref, dtype):
90
        # TODO(@jroesch): this piece of code improperly uses type variables.
91
        n = te.var("n")
92 93 94 95
        s1 = (5, n, 5)
        s2 = (n, 1)
        t1 = relay.TensorType(s1)
        t2 = relay.TensorType(s2)
96 97
        x = relay.var("x", t1, dtype=dtype)
        y = relay.var("y", t2, dtype=dtype)
98 99
        z = opfunc(x, y)
        # test printer
100
        assert ("{}(%x, %y)".format(z.op.name)) in z.astext()
Zhi committed
101 102
        zz = run_infer_type(z)
        assert zz.checked_type == t1
103

104 105 106
        if ref is not None:
            t1 = relay.TensorType((5, 10, 5))
            t2 = relay.TensorType((5, 10, 5))
107 108
            x = relay.var("x", t1, dtype=dtype)
            y = relay.var("y", t2, dtype=dtype)
109
            z = opfunc(x, y)
110 111
            x_data = np.random.rand(5, 10, 5).astype(dtype)
            y_data = np.random.rand(5, 10, 5).astype(dtype)
112
            ref_res = ref(x_data, y_data)
113
            func = relay.Function([x, y], z)
114

115 116 117
            for target, ctx in ctx_list():
                # use graph by execuor default for testing, as we need
                # create function explicitly to avoid constant-folding.
118 119
                if dtype ==  'float16' and target == 'cuda' and not have_fp16(tvm.gpu(0).compute_version):
                    continue
120 121 122
                intrp = relay.create_executor("graph", ctx=ctx, target=target)
                op_res = intrp.evaluate(func)(x_data, y_data)
                np.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=0.01)
123 124

    for opfunc, ref in [(relay.add, np.add),
125 126
                        (relay.subtract, np.subtract),
                        (relay.multiply, np.multiply),
127 128 129
                        (relay.divide, np.divide),
                        (relay.floor_divide, np.floor_divide),
                        (relay.floor_mod, np.fmod)]:
130 131
        for dtype in ['float16', 'float32']:
            check_binary_op(opfunc, ref, dtype)
132

133

134 135 136 137 138 139
def test_expand_dims():
    # based on topi test
    def verify_expand_dims(dshape, dtype, oshape, axis, num_newaxis):
        x = relay.Var("x", relay.TensorType(dshape, dtype))
        func = relay.Function([x], relay.expand_dims(x, axis, num_newaxis))
        for target, ctx in ctx_list():
140 141
            if dtype ==  'float16' and target == 'cuda' and not have_fp16(tvm.gpu(0).compute_version):
                continue
142 143 144 145 146
            data = np.random.uniform(size=dshape).astype(dtype)
            ref_res = data.reshape(oshape)
            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)
147 148 149
    for dtype in ['float16', 'float32']:
        verify_expand_dims((3, 10), dtype, (3, 10, 1, 1), 2, 2)
        verify_expand_dims((3, 10), dtype, (1, 3, 10), -3, 1)
150 151


152
def test_bias_add():
153 154 155
    for dtype in ['float16', 'float32']:
        xshape=(10, 2, 3, 4)
        bshape=(2,)
156
        rtol = 1e-2 if dtype == 'float16' else 1e-5
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        x = relay.var("x", shape=xshape, dtype=dtype)
        bias = relay.var("bias", dtype=dtype)
        z = relay.nn.bias_add(x, bias)
        zz = run_infer_type(z)
        assert "axis=" not in zz.astext()
        assert zz.args[1].checked_type == relay.TensorType(bshape, dtype)

        func = relay.Function([x, bias], z)
        x_data = np.random.uniform(size=xshape).astype(dtype)
        y_data = np.random.uniform(size=bshape).astype(dtype)
        ref_res = x_data + y_data.reshape((2, 1, 1))
        for target, ctx in ctx_list():
            if dtype ==  'float16' and target == 'cuda' and not have_fp16(tvm.gpu(0).compute_version):
                continue
            intrp = relay.create_executor("graph", ctx=ctx, target=target)
            op_res = intrp.evaluate(func)(x_data, y_data)
            np.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=rtol)
174 175


176
def test_expand_dims_infer_type():
177
    for dtype in ['float16', 'float32']:
178
        n, t, d = te.size_var("n"), te.size_var("t"), 100
179 180 181 182 183
        x = relay.var("x", shape=(n, t, d), dtype=dtype)
        y = relay.expand_dims(x, axis=2)
        assert "axis=2" in y.astext()
        yy = run_infer_type(y)
        assert yy.checked_type == relay.TensorType((n, t, 1, 100), dtype)
184 185


186
def test_softmax():
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    for dtype in ['float16', 'float32']:
        # Softmax accuracy for float16 is poor
        if dtype == 'float16':
            return
        shape = (10, 4)
        x = relay.var("x", shape=shape, dtype=dtype)
        y = relay.nn.softmax(x, axis=1)
        assert "nn.softmax" in y.astext()
        yy = run_infer_type(y)
        assert yy.checked_type == relay.TensorType(shape, dtype)
        func = relay.Function([x], y)
        x_data = np.random.uniform(size=shape).astype(dtype)
        ref_res = topi.testing.softmax_python(x_data)
        for target, ctx in ctx_list():
            intrp = relay.create_executor("graph", ctx=ctx, target=target)
            op_res = intrp.evaluate(func)(x_data)
            np.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)
204 205


206
def test_log_softmax():
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    for dtype in ['float16', 'float32']:
        # Softmax accuracy for float16 is poor
        if dtype == 'float16':
            return
        shape = (10, 4)
        x = relay.var("x", shape=shape, dtype=dtype)
        y = relay.nn.log_softmax(x, axis=1)
        assert "nn.log_softmax" in y.astext()
        yy = run_infer_type(y)
        assert yy.checked_type == relay.TensorType(shape, dtype)
        func = relay.Function([x], y)
        x_data = np.random.uniform(size=shape).astype(dtype)
        ref_res = topi.testing.log_softmax_python(x_data)
        for target, ctx in ctx_list():
            intrp = relay.create_executor("graph", ctx=ctx, target=target)
            op_res = intrp.evaluate(func)(x_data)
            np.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)
224

225

226
def test_concatenate():
227
    for dtype in ['float16', 'float32']:
228
        n, t, d = te.size_var("n"), te.size_var("t"), 100
229 230 231 232 233 234
        x = relay.var("x", shape=(n, t, d))
        y = relay.var("y", shape=(n, t, d))
        z = relay.concatenate((x, y), axis=-1)
        assert "axis=" in z.astext()
        zz = run_infer_type(z)
        assert zz.checked_type == relay.TensorType((n, t, 200))
235

236 237 238 239
        x = relay.exp(x)
        z = relay.concatenate((x, y), axis=2)
        zz = run_infer_type(z)
        assert zz.checked_type == relay.TensorType((n, t, 200))
240

241 242 243
        z = relay.concatenate((x, y), axis=1)
        zz = run_infer_type(z)
        assert zz.checked_type == relay.TensorType((n, t + t, 100))
244

245 246 247 248 249 250 251 252 253 254 255
        # check shape mismatches (the following case is expected to raise tvm._ffi.base.TVMError.
        try:
            x = relay.var('p1', shape=(2, 5))
            y = relay.var('p2', shape=(2, 3))
            c = relay.concatenate([x, y], axis=0)
            func = relay.Function([x, y], c)
            zz = run_infer_type(func)
        except tvm._ffi.base.TVMError:
            pass
        else:
            assert False
256

257 258 259 260 261 262 263 264 265 266 267
        x = relay.var("x", shape=(10, 5), dtype=dtype)
        y = relay.var("y", shape=(10, 5), dtype=dtype)
        t = relay.var("z", shape=(), dtype=dtype)
        z = relay.concatenate((x, y), axis=1)
        z = relay.add(z, t)
        # Check result.
        func = relay.Function([x, y, t], z)
        x_data = np.random.rand(10, 5).astype(dtype)
        y_data = np.random.rand(10, 5).astype(dtype)
        t_data = np.random.uniform(size=()).astype(dtype)
        ref_res = np.concatenate((x_data, y_data), axis=1) + t_data
268

269 270 271 272 273 274 275 276 277
        for target, ctx in ctx_list():
            if dtype ==  'float16' and target == 'cuda' and not have_fp16(tvm.gpu(0).compute_version):
                continue
            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, y_data, t_data)
            tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=0.01)
            op_res2 = intrp2.evaluate(func)(x_data, y_data, t_data)
            tvm.testing.assert_allclose(op_res2.asnumpy(), ref_res, rtol=0.01)
278

279
def test_dropout():
280
    for dtype in ['float16', 'float32']:
281
        n, t, d = te.size_var("n"), te.size_var("t"), te.size_var("d")
282 283 284 285 286 287
        input_ty = relay.TensorType((n, t, d), dtype)
        x = relay.var("x", input_ty)
        y = relay.nn.dropout(x, rate=0.75)
        assert "rate=" in y.astext()
        yy = run_infer_type(y)
        assert yy.checked_type == input_ty
288 289 290


def test_batch_norm():
291 292 293 294 295 296 297 298 299 300 301
    for dtype in ['float16', 'float32']:
        # beta and gamma ignored
        data = relay.var("data", relay.TensorType((3, 2, 1), dtype))
        beta = relay.var("beta", relay.TensorType((2,), dtype))
        gamma = relay.var("gamma", relay.TensorType((2,), dtype))
        moving_mean = relay.var("moving_mean", relay.TensorType((2,), dtype))
        moving_var = relay.var("moving_var", relay.TensorType((2,), dtype))
        y = relay.nn.batch_norm(data, gamma, beta, moving_mean, moving_var,
                                center=False, scale=False)
        yy = run_infer_type(y.astuple())
        assert "center=" in yy.astext()
302
        assert yy.checked_type == relay.ty.TupleType(tvm.runtime.convert([
303 304 305 306 307 308 309 310 311 312 313 314 315
            relay.TensorType((3, 2, 1), dtype),
            relay.TensorType((2,), dtype),
            relay.TensorType((2,), dtype)
        ]))

        beta = relay.var("beta", relay.TensorType((3,), dtype))
        gamma = relay.var("gamma", relay.TensorType((3,), dtype))
        moving_mean = relay.var("moving_mean", relay.TensorType((3,), dtype))
        moving_var = relay.var("moving_var", relay.TensorType((3,), dtype))

        y = relay.nn.batch_norm(data, gamma, beta, moving_mean, moving_var,
                                axis=0, center=False, scale=False)
        yy = run_infer_type(y.astuple())
316
        assert yy.checked_type == relay.ty.TupleType(tvm.runtime.convert([
317 318 319 320 321 322 323 324 325 326 327 328 329 330
            relay.ty.TensorType((3, 2, 1), dtype),
            relay.ty.TensorType((3,), dtype),
            relay.ty.TensorType((3,), dtype)
        ]))

        # axis=-1
        data = relay.var("data", relay.TensorType((1, 2, 3), dtype))
        beta = relay.var("beta", relay.TensorType((3,), dtype))
        gamma = relay.var("gamma", relay.TensorType((3,), dtype))
        moving_mean = relay.var("moving_mean", relay.TensorType((3,), dtype))
        moving_var = relay.var("moving_var", relay.TensorType((3,), dtype))
        y = relay.nn.batch_norm(data, gamma, beta, moving_mean, moving_var,
                                axis=-1, center=False, scale=False)
        yy = run_infer_type(y.astuple())
331
        assert yy.checked_type == relay.ty.TupleType(tvm.runtime.convert([
332 333 334 335
            relay.ty.TensorType((1, 2, 3), dtype),
            relay.ty.TensorType((3,), dtype),
            relay.ty.TensorType((3,), dtype)
        ]))
336

337 338 339 340 341 342 343 344 345 346
@pytest.mark.xfail
def test_dense_type_check():
    dtype = 'float16'
    n, c , h, w = 2, 2 , 2 ,2
    x = relay.var("x", relay.TensorType((n, c, h, w), dtype))
    # it should fail since it does not match with m(2)
    mismatch_w = 3
    w = relay.var("w", relay.TensorType((2, mismatch_w), dtype))
    y = relay.nn.dense(x, w)
    yy = run_infer_type(y)
347

348
def test_dense():
349 350 351 352
    for dtype in ['float16', 'float32']:
        # Dense accuracy for float16 is poor
        if dtype == 'float16':
            return
353
        n, c , h, w = te.size_var("n"), te.size_var("c"), te.size_var("h"), te.size_var("w")
354 355 356 357 358 359
        x = relay.var("x", relay.TensorType((n, c, h, w), dtype))
        w = relay.var("w", relay.TensorType((2, w), dtype))
        y = relay.nn.dense(x, w, units=2)
        assert "units=2" in y.astext()
        yy = run_infer_type(y)
        assert yy.checked_type == relay.TensorType((n, c, h, 2), dtype)
360

361
        n, c , h, w = te.size_var("n"), te.size_var("c"), te.size_var("h"), 2
362
        x = relay.var("x", relay.TensorType((n, c, h, w), dtype))
363
        wh, ww = te.size_var("wh"), te.size_var("ww")
364 365 366 367
        w = relay.var("w", relay.TensorType((ww, wh), dtype))
        y = relay.nn.dense(x, w)
        yy = run_infer_type(y)
        assert yy.checked_type == relay.TensorType((n, c, h, ww), dtype)
368

369
        n, c , h, w = te.size_var("n"), te.size_var("c"), te.size_var("h"), 2
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
        x = relay.var("x", relay.TensorType((n, c, h, w), dtype))
        w = relay.var("w", relay.IncompleteType())
        y = relay.nn.dense(x, w, units=2)
        yy = run_infer_type(y)
        assert yy.checked_type == relay.TensorType((n, c, h, 2), dtype)

        x = relay.var("x", shape=(10, 5), dtype=dtype)
        w = relay.var("w", shape=(2, 5), dtype=dtype)
        z = relay.nn.dense(x, w)

        # Check result.
        func = relay.Function([x, w], z)
        x_data = np.random.rand(10, 5).astype(dtype)
        w_data = np.random.rand(2, 5).astype(dtype)
        ref_res = np.dot(x_data, w_data.T)

        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, w_data)
            tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5)
            op_res2 = intrp2.evaluate(func)(x_data, w_data)
            tvm.testing.assert_allclose(op_res2.asnumpy(), ref_res, rtol=1e-5)
393 394


395 396 397 398
def test_dense_dtype():
    data_dtype = 'uint8'
    weight_dtype = 'int8'
    out_dtype = 'uint8'
399
    n, c , h, w = te.size_var("n"), te.size_var("c"), te.size_var("h"), te.size_var("w")
400 401 402 403 404 405 406 407 408 409
    x = relay.var("x", relay.TensorType((n, c, h, w), data_dtype))
    w = relay.var("w", relay.TensorType((2, w), weight_dtype))
    y = relay.nn.dense(x, w, units=2, out_dtype=out_dtype)
    assert "units=2" in y.astext()
    yy = run_infer_type(y)
    assert yy.checked_type == relay.TensorType((n, c, h, 2), out_dtype)
    assert run_infer_type(yy.args[0]).checked_type.dtype == 'uint8'
    assert run_infer_type(yy.args[1]).checked_type.dtype == 'int8'


410
def test_bitserial_dense():
411
    m, k = te.size_var("m"), te.size_var("k")
412 413 414 415 416 417 418 419
    x = relay.var("x", relay.TensorType((m, k), "int16"))
    w = relay.var("w", relay.TensorType((k, 32), "int16"))
    y = relay.nn.bitserial_dense(x, w, units=32)
    "units=8" in y.astext()
    yy = run_infer_type(y)
    assert yy.checked_type == relay.TensorType((m, 32), "int16")


420
if __name__ == "__main__":
421
    test_concatenate()
422
    test_bias_add()
423
    test_unary_op()
424
    test_binary_op()
425
    test_expand_dims_infer_type()
426
    test_expand_dims()
427
    test_softmax()
428
    test_log_softmax()
429 430
    test_dropout()
    test_batch_norm()
431
    test_dense()
432
    test_bitserial_dense()
433
    test_dense_dtype()