test_tracing.py 7.7 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 16
import megengine
import megengine.module as M
17
from megengine import cgtools, tensor
18
from megengine.core._trace_option import set_tensor_shape
M
Megvii Engine Team 已提交
19
from megengine.core.ops import builtin as ops
20
from megengine.core.tensor import megbrain_graph as G
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
from megengine.jit import exclude_from_trace, trace


27
def load_and_inference(file, inp_data):
28
    cg, _, out_list = G.load_graph(file)
29 30 31 32
    inputs = cgtools.get_dep_vars(out_list, "Host2DeviceCopy")
    replace_dict = {}
    inp_node_list = []
    for i in inputs:
33
        inp_node = G.InputNode(
34 35 36 37 38
            device="xpux", dtype=inputs[0].dtype, graph=inputs[0].graph
        )
        replace_dict[i] = inp_node.outputs[0]
        inp_node_list.append(inp_node)
    new_out = cgtools.replace_vars(out_list, replace_dict)
39
    out_node_list = [G.OutputNode(i) for i in new_out]
40 41 42 43 44 45 46 47 48 49
    new_out_list = [i.outputs[0] for i in out_node_list]
    new_cg = new_out_list[0].graph
    func = new_cg.compile(new_out_list)
    for node, value in zip(inp_node_list, inp_data):
        node.set_value(as_raw_tensor(value)._dev_tensor())
    func.execute()
    out_data_list = [o.get_value().numpy() for o in out_node_list]
    return out_data_list


M
Megvii Engine Team 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
def test_trace():
    for symbolic in [False, True]:

        @trace(symbolic=symbolic)
        def f(x):
            op = ops.Elemwise(mode="negate")
            (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):
            neg = ops.Elemwise(mode="negate")
            (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
            neg = ops.Elemwise(mode="negate")
            (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 已提交
107 108 109


def test_dump():
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    @trace(symbolic=True, capture_as_const=True)
    def f(a, b):
        op = ops.Elemwise(mode="add")
        (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()
    f.dump(file)
    file.seek(0)
    result = load_and_inference(file, [a, b])
    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):
        op = ops.Elemwise(mode="mul")
        (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)
    result = load_and_inference(file, [x])
    np.testing.assert_equal(result[0], y)


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

M
Megvii Engine Team 已提交
155 156
    @trace(symbolic=True, capture_as_const=True)
    def f(x):
157 158
        op = ops.Elemwise(mode="mul")
        (y,) = apply(op, x, p)
M
Megvii Engine Team 已提交
159 160
        return y

161
    x = as_raw_tensor([3]).numpy()
M
Megvii Engine Team 已提交
162 163 164 165 166 167
    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()
168
    f.dump(file, optimize_for_inference=False)
169
    file.seek(0)
170
    cg, _, outputs = G.load_graph(file)
171 172 173 174 175
    (out,) = outputs
    assert (
        cgtools.get_owner_opr_type(cgtools.get_owner_opr_inputs(out)[1])
        == "SharedDeviceTensor"
    )
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194


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

        @trace(symbolic=symbolic, profiling=True)
        def f(x):
            op = ops.Elemwise(mode="negate")
            (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")
195 196


197
@pytest.mark.skip(reason="could not disable opt_level")
198 199 200 201 202 203 204 205 206 207 208
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()
209 210
    f.dump(out, optimize_for_inference=False)
    *_, outputs = G.load_graph(out)
211 212 213
    oprs_1 = cgtools.get_oprs_seq(outputs)

    g(tensor(1.0))
214 215
    g.dump(out, optimize_for_inference=False)
    *_, outputs = G.load_graph(out)
216 217 218 219 220
    oprs_2 = cgtools.get_oprs_seq(outputs)

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


221
@pytest.mark.skip(reason="could not disable opt_level")
222 223 224 225 226 227 228 229 230 231 232
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()
233 234
    f.dump(out, optimize_for_inference=False)
    *_, outputs = G.load_graph(out)
235 236 237
    oprs_1 = cgtools.get_oprs_seq(outputs)

    g(tensor(1.0), tensor(2.0))
238 239
    g.dump(out, optimize_for_inference=False)
    *_, outputs = G.load_graph(out)
240 241 242 243 244 245 246 247 248 249 250 251
    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))
252
    f.dump(out, enable_io16xc32=True)
253

254
    res = G.load_graph(out)
255 256
    computing_input = res.output_vars_list[0].owner.inputs[0]
    assert computing_input.dtype == np.float16
257 258 259 260 261 262 263 264 265 266 267 268


def test_trace_cvt_bool():
    set_tensor_shape(True)
    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)
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285


def test_trace_reshape():
    for symbolic in [False, True]:
        set_tensor_shape(True)
        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)