test_tracing.py 10.6 KB
Newer Older
1 2 3 4 5 6 7 8
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
M
Megvii Engine Team 已提交
9
import io
10
from tempfile import mkstemp
M
Megvii Engine Team 已提交
11

M
Megvii Engine Team 已提交
12
import numpy as np
13
import pytest
M
Megvii Engine Team 已提交
14

15
import megengine.core.tensor.megbrain_graph as G
16
import megengine.functional as F
17
from megengine import cgtools, tensor
18
from megengine.core._trace_option import set_symbolic_shape
M
Megvii Engine Team 已提交
19
from megengine.core.ops import builtin as ops
20
from megengine.core.ops.builtin import Elemwise
M
Megvii Engine Team 已提交
21 22
from megengine.core.tensor.core import apply
from megengine.core.tensor.raw_tensor import as_raw_tensor
23
from megengine.functional import exp, log
M
Megvii Engine Team 已提交
24 25 26 27 28 29 30 31
from megengine.jit import exclude_from_trace, trace


def test_trace():
    for symbolic in [False, True]:

        @trace(symbolic=symbolic)
        def f(x):
32
            op = ops.Elemwise(Elemwise.Mode.NEGATE)
M
Megvii Engine Team 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
            (y,) = apply(op, x)
            return y

        x = as_raw_tensor([1]).numpy()
        y = f.__wrapped__(as_raw_tensor(x)).numpy()

        for i in range(3):
            np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)


def test_exclude_from_trace():
    for symbolic in [False, True]:

        @trace(symbolic=symbolic)
        def f(x):
48
            neg = ops.Elemwise(Elemwise.Mode.NEGATE)
M
Megvii Engine Team 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
            (x,) = apply(neg, x)
            with exclude_from_trace():
                if i % 2:
                    (x,) = apply(neg, x)
            (x,) = apply(neg, x)
            return x

        x = as_raw_tensor([1]).numpy()

        for i in range(3):
            y = f.__wrapped__(as_raw_tensor(x)).numpy()
            np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)


def test_print_in_trace():
    for symbolic in [False]:  # cannot read value in symbolic mode

        @trace(symbolic=symbolic)
        def f(x):
            nonlocal buf
69
            neg = ops.Elemwise(Elemwise.Mode.NEGATE)
M
Megvii Engine Team 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83
            (x,) = apply(neg, x)
            buf = x.numpy()
            (x,) = apply(neg, x)
            return x

        buf = None
        x = as_raw_tensor([1]).numpy()

        for i in range(3):
            y = f.__wrapped__(as_raw_tensor(x)).numpy()
            z = buf
            buf = None
            np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)
            np.testing.assert_equal(z, buf)
M
Megvii Engine Team 已提交
84 85 86


def test_dump():
87 88
    @trace(symbolic=True, capture_as_const=True)
    def f(a, b):
89
        op = ops.Elemwise(Elemwise.Mode.ADD)
90 91 92 93 94 95 96 97 98 99 100
        (y,) = apply(op, a, b)
        return y

    a = as_raw_tensor([2]).numpy()
    b = as_raw_tensor([4]).numpy()
    y = f.__wrapped__(as_raw_tensor(a), as_raw_tensor(b)).numpy()

    for i in range(3):
        np.testing.assert_equal(f(as_raw_tensor(a), as_raw_tensor(b)).numpy(), y)

    file = io.BytesIO()
101 102 103 104
    dump_info = f.dump(file)
    assert dump_info.nr_opr == 3
    np.testing.assert_equal(dump_info.inputs, ["h2d[0]", "h2d[2]"])
    np.testing.assert_equal(dump_info.outputs, ["ADD(h2d[0],h2d[2])[4]"])
105
    file.seek(0)
106
    result = cgtools.load_and_inference(file, [a, b])
107 108 109 110 111 112 113 114
    np.testing.assert_equal(result[0], y)


def test_capture_dump():
    a = as_raw_tensor([2])

    @trace(symbolic=True, capture_as_const=True)
    def f(x):
115
        op = ops.Elemwise(Elemwise.Mode.MUL)
116 117 118 119 120 121 122 123 124 125 126 127
        (y,) = apply(op, x, a)
        return y

    x = as_raw_tensor([3]).numpy()
    y = f.__wrapped__(as_raw_tensor(x)).numpy()

    for i in range(3):
        np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)

    file = io.BytesIO()
    f.dump(file)
    file.seek(0)
128
    result = cgtools.load_and_inference(file, [x])
129 130 131 132 133 134
    np.testing.assert_equal(result[0], y)


def test_dump_volatile():
    p = as_raw_tensor([2])

M
Megvii Engine Team 已提交
135 136
    @trace(symbolic=True, capture_as_const=True)
    def f(x):
137
        op = ops.Elemwise(Elemwise.Mode.MUL)
138
        (y,) = apply(op, x, p)
M
Megvii Engine Team 已提交
139 140
        return y

141
    x = as_raw_tensor([3]).numpy()
M
Megvii Engine Team 已提交
142 143 144 145 146 147
    y = f.__wrapped__(as_raw_tensor(x)).numpy()

    for i in range(3):
        np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)

    file = io.BytesIO()
148
    f.dump(file, optimize_for_inference=False)
149
    file.seek(0)
150
    cg, _, outputs = G.load_graph(file)
151 152 153
    (out,) = outputs
    assert (
        cgtools.get_owner_opr_type(cgtools.get_owner_opr_inputs(out)[1])
154
        == "ImmutableTensor"
155
    )
156 157 158 159 160 161 162


def test_trace_profiler():
    for symbolic in [False, True]:

        @trace(symbolic=symbolic, profiling=True)
        def f(x):
163
            op = ops.Elemwise(Elemwise.Mode.NEGATE)
164 165 166 167 168 169 170 171 172 173 174
            (y,) = apply(op, x)
            return y

        x = as_raw_tensor([1]).numpy()
        y = f.__wrapped__(as_raw_tensor(x)).numpy()

        f(as_raw_tensor(x))
        f(as_raw_tensor(x))  # XXX: has to run twice

        out = f.get_profile()
        assert out.get("profiler")
175 176


177
@pytest.mark.skip(reason="could not disable opt_level")
178 179 180 181 182 183 184 185 186 187 188
def test_goptions_log_exp():
    @trace(symbolic=True, opt_level=0, capture_as_const=True)
    def f(x):
        return log(exp(x))

    @trace(symbolic=True, opt_level=1, capture_as_const=True)
    def g(x):
        return log(exp(x))

    f(tensor(1.0))
    _, out = mkstemp()
189 190
    f.dump(out, optimize_for_inference=False)
    *_, outputs = G.load_graph(out)
191 192 193
    oprs_1 = cgtools.get_oprs_seq(outputs)

    g(tensor(1.0))
194 195
    g.dump(out, optimize_for_inference=False)
    *_, outputs = G.load_graph(out)
196 197 198 199 200
    oprs_2 = cgtools.get_oprs_seq(outputs)

    assert len(oprs_1) - len(oprs_2) == 2


201
@pytest.mark.skip(reason="could not disable opt_level")
202 203 204 205 206 207 208 209 210 211 212
def test_goptions_log_sum_exp():
    @trace(symbolic=True, opt_level=0, capture_as_const=True)
    def f(x, y):
        return log(exp(x) + exp(y))

    @trace(symbolic=True, opt_level=1, capture_as_const=True)
    def g(x, y):
        return log(exp(x) + exp(y))

    f(tensor(1.0), tensor(2.0))
    _, out = mkstemp()
213 214
    f.dump(out, optimize_for_inference=False)
    *_, outputs = G.load_graph(out)
215 216 217
    oprs_1 = cgtools.get_oprs_seq(outputs)

    g(tensor(1.0), tensor(2.0))
218 219
    g.dump(out, optimize_for_inference=False)
    *_, outputs = G.load_graph(out)
220 221 222 223 224 225 226 227 228 229 230 231
    oprs_2 = cgtools.get_oprs_seq(outputs)

    assert len(oprs_1) - len(oprs_2) == 2


def test_optimize_for_inference():
    @trace(symbolic=True, capture_as_const=True)
    def f(x):
        return exp(x)

    _, out = mkstemp()
    f(tensor(5.0))
232
    f.dump(out, enable_io16xc32=True)
233

234
    res = G.load_graph(out)
235 236
    computing_input = res.output_vars_list[0].owner.inputs[0]
    assert computing_input.dtype == np.float16
237 238


239 240 241
def test_optimize_for_inference_broadcast():
    a = tensor(np.ones(1, dtype=np.float32))

242
    @trace(capture_as_const=True, symbolic_shape=True)
243 244 245 246 247 248 249 250
    def f():
        (b,) = apply(ops.Broadcast(), a, tensor([1, 10], dtype=np.int32))
        return b

    f()
    f.dump(io.BytesIO())


251
def test_trace_cvt_bool():
252
    set_symbolic_shape(True)
253 254 255 256 257 258 259 260
    x = tensor([0], dtype=np.int32)

    @trace(symbolic=True)
    def f(x):
        return x.shape[0] == 0

    for i in range(3):
        np.testing.assert_equal(f(x).numpy()[0], False)
261 262 263 264


def test_trace_reshape():
    for symbolic in [False, True]:
265
        set_symbolic_shape(True)
266 267 268 269 270 271 272 273 274 275 276 277
        x1 = tensor(np.random.randn(2, 10, 10))
        x2 = tensor(np.random.randn(4, 10, 10))
        x3 = tensor(np.random.randn(8, 10, 10))

        @trace(symbolic=symbolic, capture_as_const=True)
        def f(x):
            y = x.reshape(x.shape[0], 100)
            return y

        f(x1)
        f(x2)
        f(x3)
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310


def test_trace_topk():
    x = tensor([5, 2, 7, 1, 0, 3, 2])

    @trace(symbolic=True)
    def f(x):
        y = F.topk(x, 3)
        np.testing.assert_equal(y[0].shape.numpy(), np.array([3,]))
        return y

    for i in range(3):
        f(x)


def test_trace_warp_perspective():
    inp_shape = (1, 1, 4, 4)
    x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
    M_shape = (1, 3, 3)
    M = tensor(
        np.array(
            [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
        ).reshape(M_shape)
    )

    @trace(symbolic=True)
    def f(x, M):
        out = F.warp_perspective(x, M, (2, 2))
        np.testing.assert_equal(out.shape.numpy(), np.array([1, 1, 2, 2]))
        return out

    for i in range(1):
        f(x, M)
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 336 337 338 339 340 341 342 343


def test_raise_on_trace():
    step_count = 0
    catch_count = 0
    bad_step = 10

    class CatchMe(Exception):
        pass

    a = tensor([1, 2, 3, 4])
    b = tensor([5, 6, 7, 8])
    c = tensor([9, 0, 1, 2])

    @trace
    def add_abc(a, b, c):
        print("Hello")
        ps = a + b
        result = ps + c
        if step_count == bad_step:
            raise CatchMe("catch me")
        return result

    for i in range(100):
        try:
            d = add_abc(a, b, c)
        except CatchMe as e:
            catch_count += 1
        else:
            np.testing.assert_equal(d.numpy(), (a + b + c).numpy())
        step_count += 1

    assert catch_count == 1
344 345 346 347


def test_trace_broadcast():
    for symbolic in [False, True]:
348
        set_symbolic_shape(True)
349 350 351 352 353 354
        x1 = tensor(np.random.randn(3, 1, 1))
        x2 = tensor(np.random.randn(1, 4, 1))
        x3 = tensor(np.random.randn(1, 1, 5))

        @trace(symbolic=symbolic, capture_as_const=True)
        def f(x):
355
            y = F.broadcast_to(x, (3, 4, 5))
356 357 358 359 360
            return y

        f(x1)
        f(x2)
        f(x3)
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382


def test_trace_nms():
    def make_inputs(n):
        boxes = np.zeros((n, 4))
        boxes[:, :2] = np.random.rand(n, 2) * 100
        boxes[:, 2:] = np.random.rand(n, 2) * 100 + 100

        scores = np.random.rand(n)

        return tensor(boxes), tensor(scores)

    @trace(symbolic=False)
    def f(boxes, scores):
        results = F.nn.nms(boxes, scores=scores, iou_thresh=0.5, max_output=20)
        with exclude_from_trace():
            _ = F.nn.nms(boxes, scores=scores, iou_thresh=0.5)
        return results

    f(*make_inputs(10))
    f(*make_inputs(20))
    f(*make_inputs(30))
383 384 385


def test_trace_valid_broadcast():
386
    set_symbolic_shape(True)
387 388 389 390 391 392 393 394 395 396 397
    x1 = tensor(np.random.randn(1, 1))
    x2 = tensor(np.random.randn(1, 2))
    shape = (tensor([2]), tensor([2]))

    @trace(symbolic=False)
    def f(x, shape):
        y = F.broadcast_to(x, shape)
        return y

    f(x1, shape)
    f(x2, shape)
398 399 400 401 402 403 404 405 406 407 408 409


def test_clip():
    x = tensor(np.random.randn(10, 10))

    @trace(symbolic=True)
    def f(x, lower, upper):
        y = F.clip(x, lower, upper)
        return y

    for i in range(3):
        f(x, tensor([0]), tensor([1]))
410 411 412 413 414 415 416 417 418 419 420 421 422


# test returning noncontiguous tensor from trace
def test_slice():
    @trace
    def f(x):
        return x[:, 1::2]

    x = F.arange(8).reshape(2, 4)
    f(x)
    y = f(x)
    np.testing.assert_array_equal(y.numpy(), x.numpy()[:, 1::2])
    y + y