test_backend_compile_engine.py 9.58 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 tvm
19
from tvm import te
20 21
import tvm.testing
from tvm import relay
22 23 24 25 26 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
from tvm import autotvm
import topi
from tvm.relay.testing import run_infer_type
from tvm.relay.testing.temp_op_attr import TempOpAttr


@autotvm.register_topi_compute("test/conv2d_1")
def _compute_conv2d_1(cfg, input, filter, strides, padding, dilation, out_dtype):
    return topi.nn.conv2d_nchw(input, filter, strides, padding, dilation, out_dtype)

@autotvm.register_topi_schedule("test/conv2d_1")
def _schedule_conv2d_1(cfg, outs):
    return topi.generic.schedule_conv2d_nchw(outs)

@autotvm.register_topi_compute("test/conv2d_2")
def _compute_conv2d_2(cfg, input, filter, strides, padding, dilation, out_dtype):
    return topi.nn.conv2d_nchw(input, filter, strides, padding, dilation, out_dtype)

@autotvm.register_topi_schedule("test/conv2d_2")
def _schedule_conv2d_2(cfg, outs):
    return topi.generic.schedule_conv2d_nchw(outs)

def _compute_conv2d_3(input, filter, strides, padding, dilation, out_dtype):
    return topi.nn.conv2d_nchw(input, filter, strides, padding, dilation, out_dtype)

def _schedule_conv2d_3(outs):
    return topi.generic.schedule_conv2d_nchw(outs)

@tvm.target.override_native_generic_func("test_conv2d_strategy")
def _tmp_strategy(attrs, inputs, out_type, target):
    strategy = relay.op.OpStrategy()
    strategy.add_implementation(
        relay.op.strategy.wrap_compute_conv2d(_compute_conv2d_1),
        relay.op.strategy.wrap_topi_schedule(_schedule_conv2d_1),
        name="conv2d_1",
        plevel=10)
    strategy.add_implementation(
        relay.op.strategy.wrap_compute_conv2d(_compute_conv2d_2),
        relay.op.strategy.wrap_topi_schedule(_schedule_conv2d_2),
        name="conv2d_2",
        plevel=15)
    ic = inputs[0].shape[1]
    with tvm.te.SpecializedCondition(ic >= 16):
        strategy.add_implementation(
            relay.op.strategy.wrap_compute_conv2d(_compute_conv2d_3),
            relay.op.strategy.wrap_topi_schedule(_schedule_conv2d_3),
            name="conv2d_3",
            plevel=20)
    return strategy

def _create_record(task_name, dshape, wshape, target, cost):
73
    args = [te.placeholder(dshape), te.placeholder(wshape), (1, 1), (1, 1, 1, 1),
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
            (1, 1), 'float32']
    task = autotvm.task.create(task_name, args, target)
    cfg = autotvm.ConfigEntity(0, None, {}, [])
    cfg.cost = cost
    inp = autotvm.MeasureInput(target=target, task=task, config=cfg)
    result = autotvm.MeasureResult(costs=(cost,), error_no=0, all_cost=-1, timestamp=-1)
    return (inp, result)

def test_get_valid_implementations():
    target = tvm.target.create("llvm")

    def _get_impls(dshape, wshape):
        data = relay.var("data", shape=dshape)
        weight = relay.var("wshape", shape=wshape)
        out = relay.nn.conv2d(data, weight, padding=(1, 1))
        out = run_infer_type(out)
        return relay.backend.compile_engine.get_valid_implementations(
            relay.op.get("nn.conv2d"),
            out.attrs,
93
            [te.placeholder(dshape), te.placeholder(wshape)],
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
            out.checked_type,
            target)

    with TempOpAttr("nn.conv2d", "FTVMStrategy", _tmp_strategy):
        impls = _get_impls((1, 8, 7, 7), (32, 8, 3, 3))
        assert len(impls) == 2
        impls = _get_impls((1, 16, 7, 7), (32, 16, 3, 3))
        assert len(impls) == 3

def test_select_implementation():
    target = tvm.target.create("llvm")

    def _select_impl(dshape, wshape, use_autotvm=False):
        data = relay.var("data", shape=dshape)
        weight = relay.var("wshape", shape=wshape)
        out = relay.nn.conv2d(data, weight, padding=(1, 1))
        out = run_infer_type(out)
        return relay.backend.compile_engine.select_implementation(
            relay.op.get("nn.conv2d"),
            out.attrs,
114
            [te.placeholder(dshape), te.placeholder(wshape)],
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
            out.checked_type,
            target,
            use_autotvm)

    with TempOpAttr("nn.conv2d", "FTVMStrategy", _tmp_strategy):
        impl, _ = _select_impl((1, 8, 7, 7), (32, 8, 3, 3))
        assert impl.name == "conv2d_2"
        impl, _ = _select_impl((1, 8, 7, 7), (32, 8, 3, 3), True)
        assert impl.name == "conv2d_2"
        impl, _ = _select_impl((1, 16, 7, 7), (32, 16, 3, 3))
        assert impl.name == "conv2d_3"
        impl, _ = _select_impl((1, 16, 7, 7), (32, 16, 3, 3), True)
        assert impl.name == "conv2d_3"

        # add autotvm record
        records = []
        records.append(_create_record("test/conv2d_1", (1, 8, 7, 7), (32, 8, 3, 3), target, 0.5))
        records.append(_create_record("test/conv2d_1", (1, 16, 7, 7), (32, 16, 3, 3), target, 1.0))
        with target:
            with autotvm.apply_history_best(records):
                impl, _ = _select_impl((1, 8, 7, 7), (32, 8, 3, 3), True)
                assert impl.name == "conv2d_1"
                impl, _ = _select_impl((1, 16, 7, 7), (32, 16, 3, 3), True)
                assert impl.name == "conv2d_1"
139

140 141 142 143 144 145 146 147
        records.append(_create_record("test/conv2d_2", (1, 8, 7, 7), (32, 8, 3, 3), target, 0.2))
        records.append(_create_record("test/conv2d_1", (1, 16, 7, 7), (32, 16, 3, 3), target, 1.2))
        with target:
            with autotvm.apply_history_best(records):
                impl, _ = _select_impl((1, 8, 7, 7), (32, 8, 3, 3), True)
                assert impl.name == "conv2d_2"
                impl, _ = _select_impl((1, 16, 7, 7), (32, 16, 3, 3), True)
                assert impl.name == "conv2d_1"
148 149 150 151 152 153 154

def test_compile_engine():
    engine = relay.backend.compile_engine.get()
    def get_func(shape):
        x = relay.var("x", shape=shape)
        y = relay.add(x, x)
        z = relay.add(y, x)
Zhi committed
155
        f = relay.Function([x], z)
156
        mod = tvm.IRModule.from_expr(f)
Zhi committed
157
        mod = relay.transform.InferType()(mod)
158
        return mod["main"]
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    z1 = engine.lower(get_func((10,)), "llvm")
    z2 = engine.lower(get_func((10,)), "llvm")
    z3 = engine.lower(get_func(()), "llvm")
    assert z1.same_as(z2)
    assert not z3.same_as(z1)
    if tvm.context("cuda").exist:
        z4 = engine.lower(get_func(()), "cuda")
        assert not z3.same_as(z4)

    # Test JIT target
    for target in ["llvm"]:
        ctx = tvm.context(target)
        if ctx.exist:
            f = engine.jit(get_func((10,)), target)
            x = tvm.nd.array(np.ones(10).astype("float32"), ctx=ctx)
            y = tvm.nd.empty((10,), ctx=ctx)
            f(x, y)
            tvm.testing.assert_allclose(
                y.asnumpy(), x.asnumpy() * 3)
    engine.dump()

180 181 182 183 184 185
def test_compile_placeholder_bypass():
    engine = relay.backend.compile_engine.get()
    x = relay.var("x", shape=(2, 3))
    y = relay.var("y", shape=(2, 3))
    z = relay.var("z", shape=(2, 3))
    result = relay.Tuple([x, relay.op.concatenate([y, z], axis=0)])
Zhi committed
186
    func = relay.Function(relay.analysis.free_vars(result), result)
187
    with relay.build_config(opt_level=0):
188
       graph, lib, params = relay.build(tvm.IRModule.from_expr(func), 'llvm')
189

190 191 192 193 194 195 196

def test_compile_injective_with_tuple():
    x = relay.var("x", shape=(2, 3))
    y = relay.var("y", shape=(2, 3))
    x_transpose = relay.transpose(x)
    output = relay.Tuple([x_transpose, y])
    func = relay.Function([x, y], output)
197
    relay.build(tvm.IRModule.from_expr(func), 'llvm')
198 199


200 201 202 203 204
def test_compile_tuple_dup():
    x = relay.var("data", shape=(16, 16))
    log = relay.log(x)
    output = relay.Tuple([log, log])
    f = relay.Function([x], output)
205
    relay.build(tvm.IRModule.from_expr(f), 'llvm')
206 207


208 209 210
def test_compile_full():
    # Shape calculations can happen in int64. The test checks that full operator
    # can handle when shapes are not int32
211 212 213 214
    shape = (tvm.tir.IntImm('int32', 1),
             tvm.tir.IntImm('int64', 16),
             tvm.tir.IntImm('int64', 16),
             tvm.tir.IntImm('int32', 64))
215 216
    output = relay.full(relay.const(0, 'int32'), shape=shape, dtype='int32')
    f = relay.Function([], output)
217
    mod = tvm.IRModule.from_expr(f)
218 219 220 221
    mod = relay.qnn.transform.CanonicalizeOps()(mod)
    relay.build(mod, 'llvm')


222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
def test_compile_nhwc_pack():
    data = relay.var("data", shape=(1, 1, 1, 1024), dtype="uint8")
    weight = relay.var("weight", shape=(1, 1, 1024, 1001), dtype="int8")
    p2 = relay.var("p2", shape=(1, 1, 1, 1), dtype="int32")
    conv = relay.nn.conv2d(data, weight, kernel_size=(1, 1), data_layout="NHWC",
                           kernel_layout="HWIO", out_dtype="int32")
    multiply = relay.multiply(relay.const(-22, dtype='int32'), p2)
    tile = relay.tile(multiply, reps=(1, 1, 1, 1001))
    subtract = relay.subtract(conv, tile)

    func = subtract
    mod = relay.Function(relay.analysis.free_vars(func), func)
    relay.build(mod, target="llvm")


237
if __name__ == "__main__":
238 239
    test_get_valid_implementations()
    test_select_implementation()
240
    test_compile_engine()
241
    test_compile_placeholder_bypass()
242
    test_compile_injective_with_tuple()
243
    test_compile_tuple_dup()
244
    test_compile_full()
245
    test_compile_nhwc_pack()