test_pass_annotation.py 20.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
"""Unit tests for heterogeneous compilation and execution."""
18
import json
19 20 21 22 23
import numpy as np

import tvm
from tvm import relay
from tvm.contrib import graph_runtime
24
from tvm.relay.expr_functor import ExprMutator
Zhi committed
25 26 27 28 29 30 31 32 33
from tvm.relay import transform


def run_opt_pass(expr, passes):
    passes = passes if isinstance(passes, list) else [passes]
    mod = relay.Module.from_expr(expr)
    seq = transform.Sequential(passes)
    with transform.PassContext(opt_level=3):
        mod = seq(mod)
34
    return mod["main"]
35 36 37 38 39 40 41 42 43 44 45 46 47


def test_redundant_annotation():
    ctx1 = tvm.context(1)
    ctx2 = tvm.context(2)
    x = relay.var("x", shape=(3,))
    y = relay.var("y", shape=(3,))
    z = relay.var("z", shape=(3,))

    def annotated():
        add = relay.add(x, y)
        _add1 = relay.annotation.on_device(add, ctx2)
        _add2 = relay.annotation.on_device(add, ctx2)
48 49
        sub1 = relay.subtract(_add1, z)
        sub2 = relay.subtract(_add2, z)
50

51
        func = relay.Function([x, y, z], relay.Tuple([sub1, sub2]))
Zhi committed
52 53
        func = run_opt_pass(func,
                            transform.RewriteAnnotatedOps(ctx1.device_type))
54
        return func
55 56 57

    def expected():
        add = relay.add(x, y)
58 59 60 61 62
        copy_add_sub1 = relay.device_copy(add, ctx2, ctx1)
        sub1 = relay.subtract(copy_add_sub1, z)
        copy_add_sub2 = relay.device_copy(add, ctx2, ctx1)
        sub2 = relay.subtract(copy_add_sub2, z)
        func = relay.Function([x, y, z], relay.Tuple([sub1, sub2]))
63 64
        return func

Zhi committed
65 66 67
    annotated_func = annotated()
    expected_func = run_opt_pass(expected(), transform.InferType())
    assert relay.analysis.alpha_equal(annotated_func, expected_func)
68 69


70 71 72 73 74 75 76 77 78 79
def test_annotate_expr():
    ctx1 = tvm.context(1)
    ctx2 = tvm.context(2)
    x = relay.var("x", shape=(3,))
    y = relay.var("y", shape=(3,))
    z = relay.var("z", shape=(3,))

    def annotated():
        add = relay.add(x, y)
        _add = relay.annotation.on_device(add, ctx1)
80
        sub = relay.subtract(_add, z)
81
        _sub = relay.annotation.on_device(sub, ctx2)
Zhi committed
82 83
        expr = run_opt_pass(_sub,
                            transform.RewriteAnnotatedOps(ctx1.device_type))
84 85 86 87 88 89 90 91
        return expr

    def expected():
        add = relay.add(x, y)
        copy_add_sub = relay.device_copy(add, ctx1, ctx2)
        sub = relay.subtract(copy_add_sub, z)
        return sub

Zhi committed
92 93 94
    annotated_expr = annotated()
    expected_expr = run_opt_pass(expected(), transform.InferType())
    assert relay.analysis.graph_equal(annotated_expr, expected_expr)
95 96


97 98 99 100 101 102 103 104 105 106
def test_annotate_all():
    ctx1 = tvm.context(1)
    ctx2 = tvm.context(2)
    x = relay.var("x", shape=(3,))
    y = relay.var("y", shape=(3,))
    z = relay.var("z", shape=(3,))

    def annotated():
        add = relay.add(x, y)
        _add = relay.annotation.on_device(add, ctx2)
107
        sub = relay.subtract(_add, z)
108 109
        _sub = relay.annotation.on_device(sub, ctx2)

110
        func = relay.Function([x, y, z], _sub)
Zhi committed
111 112
        func = run_opt_pass(func,
                            transform.RewriteAnnotatedOps(ctx1.device_type))
113
        return func
114 115 116 117 118 119 120

    def expected():
        add = relay.add(x, y)
        sub = relay.subtract(add, z)
        func = relay.Function([x, y, z], sub)
        return func

Zhi committed
121 122 123
    annotated_func = annotated()
    expected_func = run_opt_pass(expected(), transform.InferType())
    assert relay.analysis.graph_equal(annotated_func, expected_func)
124

125

126 127 128 129 130 131 132 133 134 135 136
def test_annotate_none():
    ctx1 = tvm.context(1)
    ctx2 = tvm.context(2)
    x = relay.var("x", shape=(3,))
    y = relay.var("y", shape=(3,))
    z = relay.var("z", shape=(3,))

    def annotated():
        add = relay.add(x, y)
        sub = relay.subtract(add, z)
        func = relay.Function([x, y, z], sub)
Zhi committed
137 138
        func = run_opt_pass(func,
                            transform.RewriteAnnotatedOps(ctx1.device_type))
139 140 141 142 143 144 145 146
        return func

    def expected():
        add = relay.add(x, y)
        sub = relay.subtract(add, z)
        func = relay.Function([x, y, z], sub)
        return func

Zhi committed
147 148 149
    annotated_func = annotated()
    expected_func = run_opt_pass(expected(), transform.InferType())
    assert relay.analysis.graph_equal(annotated_func, expected_func)
150 151 152


def check_annotated_graph(annotated_func, expected_func):
Zhi committed
153 154 155
    annotated_func = run_opt_pass(annotated_func, transform.InferType())
    expected_func = run_opt_pass(expected_func, transform.InferType())
    assert relay.analysis.alpha_equal(annotated_func, expected_func)
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175


def test_conv_network():
    R""" The network is as following:
             data1     data2
               |         |
             conv2d    conv2d
                \       /
                   add
                    |
                  conv2d
    """
    batch_size = 1
    dshape = (batch_size, 64, 56, 56)
    weight = relay.var("weight", shape=(64, 64, 3, 3))
    data1 = relay.var("data1", shape=dshape)
    data2 = relay.var("data2", shape=dshape)
    dev1 = tvm.context(1)
    dev2 = tvm.context(2)

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    def original():
        conv2d_1 = relay.nn.conv2d(
            data1,
            weight,
            channels=64,
            kernel_size=(3, 3),
            padding=(1, 1))
        conv2d_2 = relay.nn.conv2d(
            data2,
            weight,
            channels=64,
            kernel_size=(3, 3),
            padding=(1, 1))
        add = relay.add(conv2d_1, conv2d_2)
        conv2d_3 = relay.nn.conv2d(
            add,
            weight,
            channels=64,
            kernel_size=(3, 3),
            padding=(1, 1))

        func = relay.Function([data1, data2, weight], conv2d_3)
Zhi committed
198 199
        func = run_opt_pass(
            func, transform.RewriteAnnotatedOps(tvm.context(3).device_type))
200 201 202
        return func


203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    def annotated():
        conv2d_1 = relay.nn.conv2d(
            data1,
            weight,
            channels=64,
            kernel_size=(3, 3),
            padding=(1, 1))
        _conv2d_1 = relay.annotation.on_device(conv2d_1, dev2)
        conv2d_2 = relay.nn.conv2d(
            data2,
            weight,
            channels=64,
            kernel_size=(3, 3),
            padding=(1, 1))
        _conv2d_2 = relay.annotation.on_device(conv2d_2, dev2)
218
        add = relay.add(_conv2d_1, _conv2d_2)
219 220
        _add = relay.annotation.on_device(add, dev1)
        conv2d_3 = relay.nn.conv2d(
221
            _add,
222 223 224 225 226 227
            weight,
            channels=64,
            kernel_size=(3, 3),
            padding=(1, 1))
        _conv2d_3 = relay.annotation.on_device(conv2d_3, dev2)

228
        func = relay.Function([data1, data2, weight], _conv2d_3)
Zhi committed
229 230
        func = run_opt_pass(
            func, transform.RewriteAnnotatedOps(tvm.context(3).device_type))
231
        return func
232

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    class ScheduleConv2d(ExprMutator):
        def __init__(self, device):
            self.device = device
            super().__init__()

        def visit_call(self, expr):
            visit = super().visit_call(expr)
            if expr.op == tvm.relay.op.get("nn.conv2d"):
                return relay.annotation.on_device(visit, self.device)
            else:
                return visit

    def annotate_with_visitor(func):
        sched = ScheduleConv2d(dev2)
        func = sched.visit(func)
Zhi committed
248 249
        func = run_opt_pass(
            func, transform.RewriteAnnotatedOps(dev1.device_type))
250 251
        return func

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    def expected():
        conv2d_1 = relay.nn.conv2d(
            data1,
            weight,
            channels=64,
            kernel_size=(3, 3),
            padding=(1, 1))
        device_copy1 = relay.device_copy(conv2d_1, dev2, dev1)
        conv2d_2 = relay.nn.conv2d(
            data2,
            weight,
            channels=64,
            kernel_size=(3, 3),
            padding=(1, 1))
        device_copy2 = relay.device_copy(conv2d_2, dev2, dev1)
        add = relay.add(device_copy1, device_copy2)
        device_copy3 = relay.device_copy(add, dev1, dev2)
        conv2d_3 = relay.nn.conv2d(
            device_copy3,
            weight,
            channels=64,
            kernel_size=(3, 3),
            padding=(1, 1))

276
        func = relay.Function([data1, data2, weight], conv2d_3)
277 278 279 280
        return func

    def check_storage_and_device_types():
        func = annotated()
Zhi committed
281 282
        func = run_opt_pass(func, [transform.RewriteAnnotatedOps(3),
                                   transform.FuseOps(2)])
283 284 285 286 287 288 289 290 291 292
        smap = relay.backend._backend.GraphPlanMemory(func)
        storage_ids = []
        device_types = []
        for _, storage_dev_type in smap.items():
            assert len(storage_dev_type) == 2
            for sid in storage_dev_type[0]:
                storage_ids.append(sid.value)
            for did in storage_dev_type[1]:
                device_types.append(did.value)
        assert len(storage_ids) == 10
293
        assert len(set(storage_ids)) == 8
294 295 296
        assert len(set(device_types)) == 2
        assert set(device_types) == {1, 2}

297 298 299 300 301 302 303 304 305 306 307 308 309
    def test_manual_annotation():
        annotated_func = annotated()
        expected_func = expected()
        check_annotated_graph(annotated_func, expected_func)
        check_storage_and_device_types()

    def test_visitor_annotation():
        annotated_func = annotate_with_visitor(original())
        expected_func = expected()
        check_annotated_graph(annotated_func, expected_func)

    test_manual_annotation()
    test_visitor_annotation()
310 311


312
def run_fusible_network(dev, tgt):
313 314 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
    R""" The network is as following:
               x     y
                \   /
                 add
                /   \
             sqrt   log
                \   /
              subtract
                  |
                 exp
    """
    x = relay.var("x", shape=(1, 10))
    y = relay.var("y", shape=(10, 10))
    x_data = np.random.rand(1, 10).astype('float32')
    y_data = np.random.rand(10, 10).astype('float32')
    tmp_add = x_data + y_data
    tmp_sqrt = np.sqrt(tmp_add)
    tmp_log = np.log(tmp_add)
    tmp_sub = np.subtract(tmp_sqrt, tmp_log)
    ref_res = np.exp(tmp_sub)

    def get_func():
        add = relay.add(x, y)
        sqrt = relay.sqrt(add)
        log = relay.log(add)
        subtract = relay.subtract(sqrt, log)
        exp = relay.exp(subtract)

        func = relay.Function([x, y], exp)
        return func

344 345
    def test_runtime(target, device, func, fallback_device=None,
                     expected_index=None):
346
        params = {"x": x_data, "y": y_data}
347 348 349 350
        config = {"opt_level": 1}
        if fallback_device:
            config["fallback_device"] = fallback_device
        with relay.build_config(**config):
351 352 353
            graph, lib, params = relay.build(
                func,
                target,
354
                params=params)
355
            contexts = [tvm.cpu(0), tvm.context(device)]
356 357 358 359
            graph_json = json.loads(graph)
            if "device_index" in graph_json["attrs"]:
                device_index = graph_json["attrs"]["device_index"][1]
                assert device_index == expected_index
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
            mod = graph_runtime.create(graph, lib, contexts)
            mod.set_input(**params)
            mod.run()
            res = mod.get_output(0).asnumpy()
            tvm.testing.assert_allclose(res, ref_res, rtol=1e-5, atol=1e-5)

    def test_fuse_log_add(device, tgt):
        """ Only log and add are fused."""
        fallback_device = tvm.context("cpu")
        target = {"cpu": "llvm", device: tgt}
        cpu_ctx = fallback_device
        dev_ctx = tvm.context(device)

        def annotated():
            add = relay.add(x, y)
            sqrt = relay.sqrt(add)
            _sqrt = relay.annotation.on_device(sqrt, dev_ctx)
            log = relay.log(add)
378
            subtract = relay.subtract(_sqrt, log)
379 380 381
            exp = relay.exp(subtract)
            _exp = relay.annotation.on_device(exp, dev_ctx)

382
            func = relay.Function([x, y], _exp)
Zhi committed
383 384
            func = run_opt_pass(
                func, transform.RewriteAnnotatedOps(cpu_ctx.device_type))
385
            return func
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401

        def expected():
            add = relay.add(x, y)
            copy_add_sqrt = relay.device_copy(add, cpu_ctx, dev_ctx)
            sqrt = relay.sqrt(copy_add_sqrt)
            log = relay.log(add)
            copy_sqrt_subtract = relay.device_copy(sqrt, dev_ctx, cpu_ctx)
            subtract = relay.subtract(copy_sqrt_subtract, log)
            copy_sub_exp = relay.device_copy(subtract, cpu_ctx, dev_ctx)
            exp = relay.exp(copy_sub_exp)

            func = relay.Function([x, y], exp)
            return func

        annotated_func = annotated()
        expected_func = expected()
402 403 404
        ctx = tvm.context(device, 0)
        dev_idx = ctx.device_type
        expected_index = [1, 1, 1, dev_idx, dev_idx, 1, 1, dev_idx, dev_idx]
405
        check_annotated_graph(annotated_func, expected_func)
406 407
        test_runtime(target, device, annotated_func, fallback_device,
                     expected_index)
408 409 410 411 412 413 414 415 416 417 418

    def test_fuse_all(device, tgt):
        """Fuse all operators."""
        fallback_device = tvm.context("cpu")
        target = {"cpu": "llvm", device: tgt}
        cpu_ctx = fallback_device
        dev_ctx = tvm.context(device)

        def annotated():
            add = relay.add(x, y)
            _add = relay.annotation.on_device(add, dev_ctx)
419
            sqrt = relay.sqrt(_add)
420
            _sqrt = relay.annotation.on_device(sqrt, dev_ctx)
421
            log = relay.log(_add)
422
            _log = relay.annotation.on_device(log, dev_ctx)
423
            subtract = relay.subtract(_sqrt, _log)
424
            _subtract = relay.annotation.on_device(subtract, dev_ctx)
425
            exp = relay.exp(_subtract)
426 427
            _exp = relay.annotation.on_device(exp, dev_ctx)

428
            func = relay.Function([x, y], _exp)
Zhi committed
429 430
            func = run_opt_pass(
                func, transform.RewriteAnnotatedOps(cpu_ctx.device_type))
431
            return func
432 433 434 435 436 437 438 439 440 441

        annotated_func = annotated()
        expected_func = get_func()
        check_annotated_graph(annotated_func, expected_func)
        test_runtime(target, device, annotated_func, fallback_device)

    def test_fallback_exp(device, tgt):
        fallback_device = tvm.context("cpu")
        target = {"cpu": "llvm", device: tgt}
        cpu_ctx = fallback_device
442
        dev_ctx = tvm.context(device)
443 444 445 446 447 448 449 450 451

        def annotated():
            add = relay.add(x, y)
            sqrt = relay.sqrt(add)
            log = relay.log(add)
            subtract = relay.subtract(sqrt, log)
            exp = relay.exp(subtract)
            _exp = relay.annotation.on_device(exp, cpu_ctx)

452
            func = relay.Function([x, y], _exp)
Zhi committed
453 454
            func = run_opt_pass(
                func, transform.RewriteAnnotatedOps(dev_ctx.device_type))
455
            return func
456

457 458 459 460 461 462 463 464 465 466 467
        def expected():
            add = relay.add(x, y)
            sqrt = relay.sqrt(add)
            log = relay.log(add)
            subtract = relay.subtract(sqrt, log)
            copy_sub_exp = relay.device_copy(subtract, dev_ctx, cpu_ctx)
            exp = relay.exp(copy_sub_exp)

            func = relay.Function([x, y], exp)
            return func

468
        annotated_func = annotated()
469
        expected_func = expected()
470 471 472
        ctx = tvm.context(device, 0)
        dev_idx = ctx.device_type
        expected_index = [dev_idx, dev_idx, dev_idx, 1, 1]
473
        check_annotated_graph(annotated_func, expected_func)
474 475
        test_runtime(target, device, annotated_func, fallback_device,
                     expected_index)
476 477

    def test_fallback_all_operators(device, tgt):
478
        target = {device: tgt, "cpu": "llvm"}
479 480 481
        annotated_func = get_func()
        expected_func = get_func()
        check_annotated_graph(annotated_func, expected_func)
482
        test_runtime(target, device, annotated_func)
483

484 485 486 487 488 489 490 491 492 493 494 495 496 497

    test_fuse_log_add(dev, tgt)
    test_fuse_all(dev, tgt)
    test_fallback_exp(dev, tgt)
    test_fallback_all_operators(dev, tgt)

def run_unpropagatable_graph(dev, tgt):
    R""" The network is as following:
            a     b  c     d
             \   /    \   /
              add      mul
                \      /
                subtract
    """
Zhi committed
498

499 500 501 502 503 504 505 506 507 508 509
    a = relay.var("a", shape=(10, 10))
    b = relay.var("b", shape=(10, 10))
    c = relay.var("c", shape=(10, 10))
    d = relay.var("d", shape=(10, 10))
    a_data = np.random.rand(10, 10).astype('float32')
    b_data = np.random.rand(10, 10).astype('float32')
    c_data = np.random.rand(10, 10).astype('float32')
    d_data = np.random.rand(10, 10).astype('float32')
    tmp_add = a_data + b_data
    tmp_mul = np.multiply(c_data, d_data)
    ref_res = np.subtract(tmp_add, tmp_mul)
Zhi committed
510

511 512 513 514
    fallback_device = tvm.context("cpu")
    target = {"cpu": "llvm", dev: tgt}
    cpu_ctx = fallback_device
    dev_ctx = tvm.context(dev)
Zhi committed
515 516

    def annotated():
517 518 519 520
        add = relay.add(a, b)
        _add = relay.annotation.on_device(add, dev_ctx)
        mul = relay.multiply(c, d)
        _mul = relay.annotation.on_device(mul, cpu_ctx)
521
        sub = relay.subtract(_add, _mul)
522
        _sub = relay.annotation.on_device(sub, dev_ctx)
523
        func = relay.Function([a, b, c, d], _sub)
Zhi committed
524 525
        func = run_opt_pass(
            func, transform.RewriteAnnotatedOps(dev_ctx.device_type))
526
        return func
Zhi committed
527 528

    def expected():
529 530 531 532 533 534
        add = relay.add(a, b)
        mul = relay.multiply(c, d)
        copy_mul_sub = relay.device_copy(mul, cpu_ctx, dev_ctx)
        sub = relay.subtract(add, copy_mul_sub)
        func = relay.Function([a, b, c, d], sub)
        return func
Zhi committed
535

536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
    annotated_func = annotated()
    expected_func = expected()
    expected_index = [2, 2, 2, 1, 1, 1, 2, 2]
    check_annotated_graph(annotated_func, expected_func)
    params = {"a": a_data, "b": b_data, "c": c_data, "d": d_data}
    config = {"opt_level": 0}
    config["fallback_device"] = fallback_device
    with relay.build_config(**config):
        graph, lib, params = relay.build(annotated_func, target, params=params)
        contexts = [tvm.cpu(0), tvm.context(dev)]
        graph_json = json.loads(graph)
        if "device_index" in graph_json["attrs"]:
            device_index = graph_json["attrs"]["device_index"][1]
            assert device_index == expected_index
        mod = graph_runtime.create(graph, lib, contexts)
        mod.set_input(**params)
        mod.run()
        res = mod.get_output(0).asnumpy()
        tvm.testing.assert_allclose(res, ref_res, rtol=1e-5, atol=1e-5)
Zhi committed
555

556

557
def test_check_run():
558
    for dev, tgt in [("opencl", "opencl"), ("cuda", "cuda"),
559
                 ("opencl", str(tvm.target.intel_graphics()))]:
560 561 562
        if not tvm.module.enabled(dev):
            print("Skip test because %s is not enabled." % dev)
            continue
563 564
        run_fusible_network(dev, tgt)
        run_unpropagatable_graph(dev, tgt)
565

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581

def test_tuple_get_item():
    dev = "cuda"
    if not tvm.module.enabled(dev):
        print("Skip test because %s is not enabled." % dev)
        return

    cpu_ctx = tvm.cpu(0)
    gpu_ctx = tvm.context(dev)

    def expected():
        x = relay.var("x", relay.ty.TensorType((3, 3, 4), "float32"))
        split = relay.op.split(x, 3)
        elem0 = relay.device_copy(split[0], gpu_ctx, cpu_ctx)
        elem1 = relay.device_copy(split[1], gpu_ctx, cpu_ctx)
        sub = elem0 - elem1
Zhi committed
582
        func = relay.Function(relay.analysis.free_vars(sub), sub)
583 584 585 586 587 588 589 590 591
        return func

    def annotated():
        x = relay.var("x", relay.ty.TensorType((3, 3, 4), "float32"))
        split = relay.op.split(x, 3)
        split = split.astuple()
        split = relay.annotation.on_device(split, gpu_ctx)
        split = relay.TupleWrapper(split, 3)
        sub = split[0] - split[1]
Zhi committed
592 593 594
        func = relay.Function(relay.analysis.free_vars(sub), sub)
        func = run_opt_pass(
            func, transform.RewriteAnnotatedOps(cpu_ctx.device_type))
595 596
        return func

Zhi committed
597 598 599
    annotated_func = annotated()
    expected_func = run_opt_pass(expected(), transform.InferType())
    assert relay.analysis.graph_equal(annotated_func, expected_func)
600 601


602 603
if __name__ == "__main__":
    test_redundant_annotation()
604
    test_annotate_expr()
605 606 607
    test_annotate_all()
    test_annotate_none()
    test_conv_network()
608
    test_check_run()
609
    test_tuple_get_item()