test_topi_conv2d.py 1.41 KB
Newer Older
1
"""Example code to do conv2d."""
2 3 4 5
import os
import numpy as np
import tvm
import topi
6
import topi.testing
7
from tvm.contrib.pickle_memoize import memoize
8 9 10
from topi.util import get_const_tuple


11
def verify_conv2d(batch, in_size, in_channel, num_filter, kernel, stride, padding):
12 13
    in_height = in_width = in_size

14
    with tvm.target.rasp():
15 16
        A = tvm.placeholder((batch, in_channel, in_height, in_width), name='A')
        W = tvm.placeholder((num_filter, in_channel, kernel, kernel), name='W')
17
        B = topi.nn.conv2d(A, W, stride, padding)
18
        s = topi.generic.schedule_conv2d_nchw([B])
19 20 21 22 23

    a_shape = get_const_tuple(A.shape)
    w_shape = get_const_tuple(W.shape)
    dtype = A.dtype

24
    @memoize("topi.tests.test_topi_conv2d.verify_conv2d")
25 26 27 28 29 30 31
    def get_ref_data():
        a_np = np.random.uniform(size=a_shape).astype(dtype)
        w_np = np.random.uniform(size=w_shape).astype(dtype)
        b_np = topi.testing.conv2d_nchw_python(a_np, w_np, stride, padding)
        return a_np, w_np, b_np

    a_np, w_np, b_np = get_ref_data()
32 33 34 35 36 37 38 39 40

    ctx = tvm.cpu(0)
    a = tvm.nd.array(a_np, ctx)
    w = tvm.nd.array(w_np, ctx)
    b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), ctx)
    func = tvm.build(s, [A, W, B], "llvm")
    func(a, w, b)
    np.testing.assert_allclose(b.asnumpy(), b_np, rtol=1e-5)

41 42
def test_conv2d():
    verify_conv2d(1, 56,  64, 64,  3, 1, 1)
43 44

if __name__ == "__main__":
45
    test_conv2d()