test_op_level1.py 17 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
Zhi committed
18
import tvm
19
import scipy
20
from tvm import relay
Zhi committed
21
from tvm.relay import transform
22
from tvm.relay.testing import ctx_list
23
import topi.testing
24
from tvm.contrib.nvcc import have_fp16
25

Zhi committed
26 27 28
def run_infer_type(expr):
    mod = relay.Module.from_expr(expr)
    mod = transform.InferType()(mod)
29
    entry = mod["main"]
Zhi committed
30 31
    return entry if isinstance(expr, relay.Function) else entry.body

32 33 34 35 36 37 38 39
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
40

41 42 43 44
def rsqrt(x):
    one = np.ones_like(x)
    return one / np.sqrt(x)

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

58 59 60
        if ref is not None:
            data = np.random.rand(*shape).astype(dtype)
            ref_res = ref(data)
61 62 63 64
            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.
65 66
                if dtype ==  'float16' and target == 'cuda' and not have_fp16(tvm.gpu(0).compute_version):
                    continue
67 68 69 70
                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)

71 72

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

86

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

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

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

117 118 119
            for target, ctx in ctx_list():
                # use graph by execuor default for testing, as we need
                # create function explicitly to avoid constant-folding.
120 121
                if dtype ==  'float16' and target == 'cuda' and not have_fp16(tvm.gpu(0).compute_version):
                    continue
122 123 124
                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)
125 126

    for opfunc, ref in [(relay.add, np.add),
127 128 129
                        (relay.subtract, np.subtract),
                        (relay.multiply, np.multiply),
                        (relay.divide, np.divide)]:
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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    for dtype in ['float16', 'float32']:
        xshape=(10, 2, 3, 4)
        bshape=(2,)
        rtol = 1e-2 if dtype is 'float16' else 1e-5
        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 178 179 180 181 182 183
    for dtype in ['float16', 'float32']:
        n, t, d = tvm.var("n"), tvm.var("t"), 100
        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 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 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
    for dtype in ['float16', 'float32']:
        n, t, d = tvm.var("n"), tvm.var("t"), 100
        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))
    
        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))
    
        z = relay.concatenate((x, y), axis=1)
        zz = run_infer_type(z)
        assert zz.checked_type == relay.TensorType((n, t + t, 100))
    
        # 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
    
        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
    
        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 281 282 283 284 285 286 287
    for dtype in ['float16', 'float32']:
        n, t, d = tvm.var("n"), tvm.var("t"), tvm.var("d")
        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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
    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()
        assert yy.checked_type == relay.ty.TupleType(tvm.convert([
            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())
        assert yy.checked_type == relay.ty.TupleType(tvm.convert([
            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())
        assert yy.checked_type == relay.ty.TupleType(tvm.convert([
            relay.ty.TensorType((1, 2, 3), dtype),
            relay.ty.TensorType((3,), dtype),
            relay.ty.TensorType((3,), dtype)
        ]))
336 337


338
def test_dense():
339 340 341 342 343 344 345 346 347 348 349
    for dtype in ['float16', 'float32']:
        # Dense accuracy for float16 is poor
        if dtype == 'float16':
            return
        n, c , h, w = tvm.var("n"), tvm.var("c"), tvm.var("h"), tvm.var("w")
        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)
350

351 352 353 354 355 356 357
        n, c , h, w = tvm.var("n"), tvm.var("c"), tvm.var("h"), 2
        x = relay.var("x", relay.TensorType((n, c, h, w), dtype))
        wh, ww = tvm.var("wh"), tvm.var("ww")
        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)
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
        n, c , h, w = tvm.var("n"), tvm.var("c"), tvm.var("h"), 2
        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)
383 384


385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
def test_dense_dtype():
    data_dtype = 'uint8'
    weight_dtype = 'int8'
    out_dtype = 'uint8'
    n, c , h, w = tvm.var("n"), tvm.var("c"), tvm.var("h"), tvm.var("w")
    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'


400 401 402 403 404 405 406 407 408 409
def test_bitserial_dense():
    m, k = tvm.var("m"), tvm.var("k")
    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")


410
if __name__ == "__main__":
411
    test_concatenate()
412
    test_bias_add()
413
    test_unary_op()
414
    test_binary_op()
415
    test_expand_dims_infer_type()
416
    test_expand_dims()
417
    test_softmax()
418
    test_log_softmax()
419 420
    test_dropout()
    test_batch_norm()
421
    test_dense()
422
    test_bitserial_dense()
423
    test_dense_dtype()