tracing.py 35.0 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 collections
M
Megvii Engine Team 已提交
10 11
import contextlib
import functools
M
Megvii Engine Team 已提交
12
import itertools
13
import json
M
Megvii Engine Team 已提交
14
import typing
M
Megvii Engine Team 已提交
15
import warnings
M
Megvii Engine Team 已提交
16 17
import weakref

M
Megvii Engine Team 已提交
18 19
import numpy as np

20
from ..core._imperative_rt import GraphProfiler
21
from ..core._imperative_rt.ops import OprAttr
22
from ..core._trace_option import set_symbolic_shape
M
Megvii Engine Team 已提交
23 24
from ..core.ops.special import Const
from ..core.tensor import megbrain_graph as G
M
Megvii Engine Team 已提交
25
from ..core.tensor.core import OpBase, TensorBase, TensorWrapperBase, apply
M
Megvii Engine Team 已提交
26
from ..core.tensor.raw_tensor import OpDef, RawTensor, as_raw_tensor
M
Megvii Engine Team 已提交
27
from ..core.tensor.tensor import Tensor
28
from .sublinear_memory_config import SublinearMemoryConfig
M
Megvii Engine Team 已提交
29 30 31 32 33 34 35 36 37 38


class TraceMismatchError(RuntimeError):
    pass


active_trace = None
skip_tracing = False


39 40 41 42 43 44 45
def is_tracing():
    if active_trace is None:
        return False
    else:
        return not skip_tracing


M
Megvii Engine Team 已提交
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
@contextlib.contextmanager
def exclude_from_trace():
    global skip_tracing
    if skip_tracing:
        yield
        return
    try:
        skip_tracing = True
        if active_trace is not None:
            active_trace._begin_excluded_region()
        yield
    finally:
        skip_tracing = False


class TensorInfo:
    __slots__ = (
        # collected attributes
        "external",
        "exported",
        "data_read",
        "shape_read",
        "value_read",
        "device",
        "dtype",
71
        "shape",
M
Megvii Engine Team 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
        "bound_data",
        # resources for execution
        "varnode",
        "data_setter",
        "shape_reader",
        "value_reader",
        "data_reader",
    )

    def __init__(self):
        self.exported = None
        self.data_read = None
        self.shape_read = None
        self.value_read = None
        self.bound_data = None

        self.data_setter = None
        self.shape_reader = None
        self.value_reader = None
        self.data_reader = None


class trace:
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    """
    Wraps a callable and provide:

    * tracing via :meth:`.trace` and :meth:`.dump`
    * accelerated evalutaion via :meth:`.__call__`

    :param function: the function will be traced.
    :param symbolic: whether to apply symbolic execution for tracing. Default: False
    :param capture_as_const: capture global vars or closures as const value. Default: False
    :param sublinear_memory_config: configuration for sublinear memory optimization.
        If not None, it enables sublinear memory optimization with given setting.
    :param profiling: whether to profile compiled trace. Default: False
    :param opt_level: optimization level for compiling trace.
    :param symbolic_shape: whether to use symbolic shape for tracing. Default: True
    """

M
Megvii Engine Team 已提交
111 112 113
    def __new__(cls, *args, **kwargs):
        if not args:
            return functools.partial(cls, **kwargs)
114
        return super().__new__(cls)
M
Megvii Engine Team 已提交
115

116 117 118 119 120 121
    def __init__(
        self,
        function,
        symbolic=False,
        capture_as_const=False,
        sublinear_memory_config: SublinearMemoryConfig = None,
122
        profiling: bool = False,
123
        opt_level: int = None,
124
        symbolic_shape: bool = True,
125
    ):
M
Megvii Engine Team 已提交
126 127 128
        self.__wrapped__ = function
        self._symbolic = symbolic
        self._capture_as_const = capture_as_const
129
        self._sublinear_memory_config = sublinear_memory_config
130 131
        self._profiling = profiling
        self._profiler = None
132
        self._graph_opt_level = opt_level
133
        self._symbolic_shape = symbolic_shape
M
Megvii Engine Team 已提交
134

135 136 137
        self._reset()

    def _reset(self):
M
Megvii Engine Team 已提交
138 139 140 141 142 143 144
        self._untraced = True
        self._tinfo = []  # handle -> TensorInfo
        self._seq = []
        self._pc = 0
        self._graph = None
        self._need_reset_nodes = None
        self._lazy_eval_graph = None
145 146
        self._lazy_eval_tensors = []
        self._lazy_eval_tensor_count = 0
M
Megvii Engine Team 已提交
147
        self._active_tensors = weakref.WeakSet()
M
Megvii Engine Team 已提交
148 149
        self._tensor_remaps = None
        self._inputs_to_restore = None
150 151
        self._arg_bindings = None
        self._kwarg_bindings = None
M
Megvii Engine Team 已提交
152 153
        self._output_bindings = None
        self._output_names = None
M
Megvii Engine Team 已提交
154

155
        set_symbolic_shape(self._symbolic_shape)
156

M
Megvii Engine Team 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170
    def _new_handle(self):
        handle = len(self._tinfo)
        info = TensorInfo()
        self._tinfo.append(info)
        return handle, info

    def _apply_op(self, op, args):
        assert not self._untraced
        # check against trace
        if self._pc >= len(self._seq):
            raise TraceMismatchError("trace should end here, but more op observed")
        record = self._seq[self._pc]
        op_, ihandles, ohandles = record
        if op != op_:
171 172 173 174 175 176
            # FIXME: will be removed once better rng implementation is done
            if isinstance(op, OprAttr) and (
                op.type in ("UniformRNG", "GaussianRNG") and op.type == op_.type
            ):
                if op.param[8:] != op_.param[8:]:
                    raise TraceMismatchError("op different from last time")
177 178
            else:
                raise TraceMismatchError("op different from last time")
M
Megvii Engine Team 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        if len(ihandles) != len(args):
            raise TraceMismatchError("op input size different from last time")

        for h, x in zip(ihandles, args):
            info = self._tinfo[h]
            if info.external:
                if (
                    x.__class__ is CompiledTensorProxy
                    and not self._tinfo[x._CompiledTensorProxy__handle].exported
                ):
                    raise TraceMismatchError(
                        "failed to capture: input was an external tensor "
                        "last time, got an internal tensor this time"
                    )
                if info.bound_data:
                    if x.__class__ is CompiledTensorProxy:
                        raise TraceMismatchError(
                            "const capture violated: was an external tensor "
                            "last time, got an internal tensor this time"
                        )
                    if x._handle != info.bound_data._handle:
200
                        if not np.array_equal(x.numpy(), info.bound_data.numpy()):
M
Megvii Engine Team 已提交
201 202 203 204
                            raise TraceMismatchError(
                                "const capture violated: got "
                                "a different tensor this time"
                            )
M
Megvii Engine Team 已提交
205 206 207 208 209 210 211 212 213 214 215 216
                else:
                    if info.dtype != x.dtype:
                        raise TraceMismatchError(
                            "failed to capture: different dtype from last time"
                        )
                    if info.device != x.device:
                        raise TraceMismatchError(
                            "failed to capture: different device from last time"
                        )
                    info.data_setter.set_value(x._dev_tensor())
            else:
                if x.__class__ is not CompiledTensorProxy:
M
Megvii Engine Team 已提交
217 218 219 220 221 222 223
                    if x not in self._tensor_remaps:
                        raise TraceMismatchError(
                            "unexpected capture: trying to use an external tensor as "
                            "input, but that input was an internal tensor last time"
                        )
                    else:
                        x = self._tensor_remaps[x]
M
Megvii Engine Team 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
                if x._CompiledTensorProxy__handle != h:
                    raise TraceMismatchError(
                        "mis-wiring: input edge to an data flow "
                        "graph node is different from last time"
                    )

        self._pc += 1
        outputs = tuple([CompiledTensorProxy(h) for h in ohandles])
        self._active_tensors.update(outputs)
        return outputs

    def _record_op(self, op, inputs, outputs):
        if skip_tracing:
            for x in inputs:
                h = getattr(x, "_TraceMixin__handle", None)
                if h is not None:
                    self._tinfo[h].data_read = True
            return

        ihandles = []
        for x in inputs:
            h = getattr(x, "_TraceMixin__handle", None)
            if h is None or (not self._capture_as_const and self._tinfo[h].exported):
                h, info = self._new_handle()
                info.external = True
                info.device = x.device
                info.dtype = x.dtype
251
                info.shape = x.shape
M
Megvii Engine Team 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
                if self._capture_as_const:
                    info.bound_data = x

            ihandles.append(h)

        ohandles = []
        for x in outputs:
            h, info = self._new_handle()
            ohandles.append(h)
            info.external = False
            TraceMixin._TraceMixin__inject(x, h)

        self._seq.append((op, tuple(ihandles), tuple(ohandles)))
        self._active_tensors.update(outputs)

267 268 269
    def _record_const(self, op, outputs):
        pass

270
    def _set_active(self, active: bool):
M
Megvii Engine Team 已提交
271
        global active_trace
272 273 274 275
        if active:
            if active_trace:
                raise NotImplementedError("sorry, not implemented: nested trace")
            active_trace = self
M
Megvii Engine Team 已提交
276
        else:
277 278 279 280 281 282 283 284 285 286 287 288
            assert active_trace is self
            active_trace = None

    def _init_trace(self, symbolic: bool):
        apply.enable(apply_with_tracing)
        apply.enable(apply_const_with_tracing)
        if symbolic:
            apply.enable(apply_symbolic_mode)
            apply.enable(apply_const_symbolic_mode)
            self._lazy_eval_graph = G.Graph()

    def _take_escaped_tensors(self):
M
Megvii Engine Team 已提交
289 290
        escaped_tensors = tuple(self._active_tensors)
        self._active_tensors.clear()
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
        return escaped_tensors

    def _lazy_eval(self, lazy_eval_graph, lazy_eval_tensors):
        active_lazy_eval_tensors = []
        visited = set()
        readers = []
        for x in lazy_eval_tensors:
            x = x()
            if x is None or x in visited:
                continue
            reader = G.OutputNode(x._LazyEvalTensor__varnode).outputs[0]
            readers.append(reader)
            active_lazy_eval_tensors.append(x)
            visited.add(x)
        self._apply_graph_options(lazy_eval_graph)
        lazy_eval_graph.compile(*readers)
        lazy_eval_graph()
        for r, x in zip(readers, active_lazy_eval_tensors):
            assign_raw_tensor(x, as_raw_tensor(r.op.get_value()))

    @contextlib.contextmanager
    def _setup(self):
        interrupted = False
M
Megvii Engine Team 已提交
314

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
        def do_enter():
            self._set_active(True)
            if self._untraced:
                self._init_trace(self._symbolic)
            else:
                apply.enable(apply_compiled_mode)
                if self._graph is None:
                    self._compile()
                self._graph.execute()

        def do_finalize():
            escaped_tensors = self._take_escaped_tensors()
            if self._untraced:
                for x in escaped_tensors:
                    info = self._tinfo[x._TraceMixin__handle]
                    info.data_read = True
M
Megvii Engine Team 已提交
331
                    x._TraceMixin__restore()
332 333 334 335 336 337
                if self._inputs_to_restore:
                    for x in self._inputs_to_restore:
                        x._TraceMixin__restore()
                if self._symbolic and self._lazy_eval_tensors:
                    # eval lazy eval tensors
                    self._lazy_eval(self._lazy_eval_graph, self._lazy_eval_tensors)
M
Megvii Engine Team 已提交
338 339
                    self._lazy_eval_graph = None
                    self._lazy_eval_tensors = None
340 341 342 343 344 345 346 347 348 349 350 351 352 353
                self._untraced = False
            else:
                # compiled_tensor leaks
                if self._pc == len(self._seq):
                    for x in escaped_tensors:
                        try:
                            assign_raw_tensor(x, as_raw_tensor(x._dev_tensor()))
                        except TraceMismatchError:
                            # TraceMismatchError thrown in do_exit
                            pass
                    self._graph.wait()
                    self._reset_exec_env()

            # reset status
M
Megvii Engine Team 已提交
354
            self._pc = 0
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
            self._tensor_remaps = None
            apply.disable(apply_with_tracing)
            apply.disable(apply_const_with_tracing)
            apply.disable(apply_symbolic_mode)
            apply.disable(apply_const_symbolic_mode)
            apply.disable(apply_compiled_mode)
            self._set_active(False)

        def do_exit():
            if not self._untraced and self._pc != len(self._seq):
                raise TraceMismatchError("premature end")
            if not self._symbolic or not self._untraced:
                for x in self._active_tensors:
                    x._dev_tensor()

        try:
            do_enter()
            yield
            do_exit()
        except:
            interrupted = True
            raise
        finally:
            do_finalize()
            if interrupted:
                self._reset()
M
Megvii Engine Team 已提交
381 382

    def _begin_excluded_region(self):
M
Megvii Engine Team 已提交
383 384 385 386
        if self._capture_as_const:
            raise RuntimeError(
                "exclude_from_trace cannot be used with capture_as_const"
            )
M
Megvii Engine Team 已提交
387 388 389 390 391 392 393 394
        if self._untraced:
            # conditionally reading a compiled tensor in excluded region
            # is permitted, so we have to assume every tensor might be read
            for x in self._active_tensors:
                info = self._tinfo[x._TraceMixin__handle]
                info.exported = True
                info.data_read = True

395 396
    def _apply_graph_options(self, graph):

397
        graph.options.seq_opt.enable_seq_comp_node_opt = False
398 399 400
        # graph opt level
        if self._graph_opt_level is not None:
            graph.options.graph_opt_level = self._graph_opt_level
401 402 403 404 405 406 407 408 409 410 411 412 413
        # sublinear
        if self._sublinear_memory_config is not None:
            graph.options.enable_sublinear_memory_opt = True
            sublinear_config = graph.options.sublinear_mem_config
            sublinear_config.lb_memory = self._sublinear_memory_config.lb_memory
            sublinear_config.genetic_nr_iter = (
                self._sublinear_memory_config.genetic_nr_iter
            )
            sublinear_config.genetic_pool_size = (
                self._sublinear_memory_config.genetic_pool_size
            )
            sublinear_config.thresh_nr_try = self._sublinear_memory_config.thresh_nr_try
            sublinear_config.num_worker = self._sublinear_memory_config.num_worker
414
        # profile
415 416
        if self._profiling:
            self._profiler = GraphProfiler(graph)
417

M
Megvii Engine Team 已提交
418 419
    def _compile(self):
        graph = self._graph = G.Graph()
420
        graph.options.no_force_inplace = True
421
        graph.options.async_exec_level = 0b100
422
        self._apply_graph_options(graph)
M
Megvii Engine Team 已提交
423 424 425 426
        # graph.options.graph_opt_level = 0
        need_reset_nodes = self._need_reset_nodes = []
        # links enforce ordering of I/O nodes
        links = ()
427
        readers = []
M
Megvii Engine Team 已提交
428 429

        if self._capture_as_const:
430
            for h in itertools.chain(self._arg_bindings, self._kwarg_bindings.values()):
M
Megvii Engine Team 已提交
431 432
                info = self._tinfo[h]
                opnode = info.data_setter = G.InputNode(
433
                    device=info.device, dtype=info.dtype, shape=info.shape, graph=graph
M
Megvii Engine Team 已提交
434 435 436 437 438
                )
                need_reset_nodes.append(opnode)
                info.varnode = opnode.outputs[0]
                links += opnode.outputs[1:]

M
Megvii Engine Team 已提交
439 440 441 442 443 444 445 446 447 448
        for op, ihandles, ohandles in self._seq:
            ivars = []
            for h in ihandles:
                info = self._tinfo[h]
                if not hasattr(info, "varnode"):
                    assert info.external
                    if info.bound_data:
                        info.varnode = graph.make_const(info.bound_data._dev_tensor())
                    else:
                        opnode = info.data_setter = G.InputNode(
449 450 451 452 453
                            *links,
                            device=info.device,
                            dtype=info.dtype,
                            shape=info.shape,
                            graph=graph,
M
Megvii Engine Team 已提交
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
                        )
                        need_reset_nodes.append(opnode)
                        info.varnode, *links = opnode.outputs

                ivars.append(info.varnode)
            ovars = apply(op, *ivars)
            assert len(ovars) == len(ohandles)
            for h, v in zip(ohandles, ovars):
                info = self._tinfo[h]
                info.varnode = v

                def add_reader(opnode):
                    nonlocal links
                    need_reset_nodes.append(opnode)
                    readers.append(opnode.outputs[0])
                    links = opnode.outputs

                if info.data_read:
                    # Shape can be obtained from data so doesn't need its own
                    # output node. On the other hand, value is read separately
                    # to leverage eager h2d copy
                    info.shape_read = False
                    opnode = info.data_reader = G.OutputNode(v, *links)
                    add_reader(opnode)
                if info.value_read:
                    opnode = info.value_reader = G.ValueOutputNode(v, *links)
                    add_reader(opnode)
                if info.shape_read:
                    opnode = info.shape_reader = G.AttrOutputNode(v, *links)
                    add_reader(opnode)

        graph.compile(*readers)

    def _reset_exec_env(self):
        for opnode in self._need_reset_nodes:
            opnode.reset()

    def _require_shape(self, handle):
        info = self._tinfo[handle]
        info.shape_read = True

    def _require_value(self, handle):
        info = self._tinfo[handle]
        info.value_read = True

    def _require_data(self, handle):
        info = self._tinfo[handle]
        info.data_read = True

    def __call__(self, *args, **kwargs):
        with self._setup():
M
Megvii Engine Team 已提交
505 506 507 508 509 510 511
            if self._capture_as_const:
                self._process_inputs(*args, **kwargs)
            outputs = self.__wrapped__(*args, **kwargs)
            if self._capture_as_const:
                self._process_outputs(outputs)
            return outputs

512 513 514 515 516 517 518 519 520 521
    def dump(
        self,
        file,
        *,
        arg_names=None,
        output_names=None,
        append=False,
        optimize_for_inference=True,
        **kwargs
    ):
522 523 524 525 526 527 528 529
        r"""Serializes trace to file system.

        :param file: output file, could be file object or filename.
        :param arg_names: names of the input tensors in the traced function.
        :param output_names: names of the output tensors in the traced function,
            use the default name if not specified.
        :param append: whether output is appended to ``file``.
            Only works when ``file`` is str.
530 531
        :param optimize_for_inference: enbale optmizations,
            will skip all optimize options if this is False. Default: True
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571

        :Keyword Arguments:

            * enable_io16xc32 --
                whether to use float16 for I/O between oprs and use
                float32 as internal computation precision. Note the output var would be
                changed to float16.
            * enable_ioc16 --
                whether to use float16 for both I/O and computation
                precision.

            * enable_hwcd4 --
                whether to use NHWCD4 data layout. This is faster on some
                OpenCL backend.
            * enable_nchw88 --
                whether to use NCHW88 data layout, currently
                used in X86 AVX backend.
            * enable_nchw44 --
                whether to use NCHW44 data layout, currently
                used in arm backend.
            * enable_nchw44_dot --
                whether to use NCHW44_dot data layout, currently
                used in armv8.2+dotprod backend.
            * enable_nchw4 --
                whether to use NCHW4 data layout, currently
                used in nvidia backend(based on cudnn).
            * enable_nchw32 --
                whether to use NCHW32 data layout, currently
                used in nvidia backend with tensorcore(based on cudnn).
            * enable_chwn4 --
                whether to use CHWN4 data layout, currently
                used in nvidia backend with tensorcore.

            * enable_fuse_conv_bias_nonlinearity: whether to fuse conv+bias+nonlinearty
                into one opr.
            * enable_fuse_conv_bias_with_z: whether to fuse conv_bias with z
                input for inference on nvidia backend(this optimization pass will
                result in mismatch of the precision of output of training and
                inference)
        """
M
Megvii Engine Team 已提交
572 573 574 575 576 577 578 579 580 581
        if not self._capture_as_const:
            raise ValueError(
                "you must specify capture_as_const=True at __init__ to use dump"
            )
        if self._untraced:
            raise RuntimeError("should run at least once before calling dump")
        if self._output_names and output_names:
            raise TypeError(
                "cannot specify output_names when output is already in dict format"
            )
M
Megvii Engine Team 已提交
582
        if output_names and not isinstance(output_names, collections.abc.Sequence):
M
Megvii Engine Team 已提交
583 584
            output_names = (output_names,)
        if output_names and len(output_names) != len(self._output_bindings):
585 586 587 588 589
            raise ValueError(
                "wrong number of output_names, should be {} values".format(
                    len(self._output_bindings)
                )
            )
M
Megvii Engine Team 已提交
590
        if arg_names and not isinstance(arg_names, collections.abc.Sequence):
M
Megvii Engine Team 已提交
591 592
            arg_names = (arg_names,)
        if arg_names and len(arg_names) != len(self._arg_bindings):
593 594 595 596 597
            raise ValueError(
                "wrong number of arg_names, should be {} values".format(
                    len(self._arg_bindings)
                )
            )
M
Megvii Engine Team 已提交
598 599 600 601 602
        output_names = output_names or self._output_names

        h2v = {}
        graph = G.Graph()

603
        for i, h in enumerate(self._arg_bindings):
M
Megvii Engine Team 已提交
604
            info = self._tinfo[h]
605 606 607 608 609 610 611
            h2v[h] = graph.make_h2d(
                dtype=info.dtype,
                device=info.device,
                shape=info.shape,
                name=arg_names[i] if arg_names else None,
            )
        for k, h in self._kwarg_bindings.items():
M
Megvii Engine Team 已提交
612
            info = self._tinfo[h]
613 614 615
            h2v[h] = graph.make_h2d(
                dtype=info.dtype, device=info.device, shape=info.shape, name=k
            )
M
Megvii Engine Team 已提交
616 617 618 619 620 621 622 623

        for op, ihandles, ohandles in self._seq:
            ivars = []
            for h in ihandles:
                info = self._tinfo[h]
                if h not in h2v:
                    assert info.external
                    assert info.bound_data
624 625 626
                    h2v[h] = graph.make_const(
                        info.bound_data.numpy(), dtype=info.dtype, device=info.device
                    )
M
Megvii Engine Team 已提交
627 628 629 630 631 632 633 634 635 636 637 638
                ivars.append(h2v[h])
            ovars = apply(op, *ivars)
            assert len(ovars) == len(ohandles)
            h2v.update(zip(ohandles, ovars))

        dest_vars = []
        for i, h in enumerate(self._output_bindings):
            v = h2v[h]
            if output_names:
                v.name = output_names[i]
            dest_vars.append(v)

639 640
        if optimize_for_inference:
            dest_vars = G.optimize_for_inference(dest_vars, **kwargs)
641

M
Megvii Engine Team 已提交
642
        if isinstance(file, str):
643 644
            permission = "wb" if append == False else "ab"
            file = open(file, permission)
645 646 647
        dump_content, dump_info = G.dump_graph(dest_vars)
        file.write(dump_content)
        return dump_info
M
Megvii Engine Team 已提交
648 649 650 651 652 653 654 655 656 657 658 659

    def _process_inputs(self, *args, **kwargs):
        if self._untraced:
            self._inputs_to_restore = []

            def record_input(x):
                if x is None:
                    return
                h, info = self._new_handle()
                info.external = False
                info.device = x.device
                info.dtype = x.dtype
660
                info.shape = x.shape
M
Megvii Engine Team 已提交
661 662 663 664
                TraceMixin._TraceMixin__inject(x, h)
                self._inputs_to_restore.append(x)
                return h

665
            self._arg_bindings = []
M
Megvii Engine Team 已提交
666 667 668 669 670 671 672
            for i, x in enumerate(args):
                x = find_raw_tensor(x)
                if x is None:
                    raise TypeError(
                        "positional arguments should all be tensor "
                        "but args[%d] cannot be recognized as one" % i
                    )
673
                self._arg_bindings.append(record_input(x))
M
Megvii Engine Team 已提交
674

675
            self._kwarg_bindings = {}
M
Megvii Engine Team 已提交
676 677 678
            for k, x in kwargs.items():
                x = find_raw_tensor(x)
                if x is not None:
679
                    self._kwarg_bindings[k] = record_input(x)
M
Megvii Engine Team 已提交
680
        else:
681
            if len(args) != len(self._arg_bindings):
M
Megvii Engine Team 已提交
682 683 684 685
                raise TraceMismatchError("positional argument length mismatch")

            self._tensor_remaps = {}

686
            for i, (h, x) in enumerate(zip(self._arg_bindings, args)):
M
Megvii Engine Team 已提交
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
                x = find_raw_tensor(x)
                if x is None:
                    raise TypeError(
                        "positional arguments should all be tensor "
                        "but args[%d] cannot be recognized as one" % i
                    )
                info = self._tinfo[h]
                if x.dtype != info.dtype:
                    raise TypeError("args[%d].dtype different from last time" % i)
                if x.device != info.device:
                    raise TypeError("args[%d].device different from last time" % i)
                info.data_setter.set_value(x._dev_tensor())
                self._tensor_remaps[x] = CompiledTensorProxy(h)

            kwargs_tensors = {}
            for k, x in kwargs.items():
                x = find_raw_tensor(x)
                if x is not None:
                    kwargs_tensors[k] = x
706 707 708
            if set(kwargs_tensors) != set(self._kwarg_bindings):
                too_many = set(kwargs_tensors) - set(self._kwarg_bindings)
                too_few = set(self._kwarg_bindings) - set(kwargs_tensors)
M
Megvii Engine Team 已提交
709 710 711 712 713 714 715 716 717 718
                if too_many:
                    raise TraceMismatchError(
                        "keyword arguments found to be tensor this time "
                        "but were non-tensor previously: %s" % " ".join(too_many)
                    )
                if too_few:
                    raise TraceMismatchError(
                        "keyword arguments found to be non-tensor this time "
                        "but were tensor previously: %s" % " ".join(too_few)
                    )
719
            for k, h in self._kwarg_bindings.items():
M
Megvii Engine Team 已提交
720 721 722 723 724 725 726 727 728 729 730
                x = kwargs_tensors[k]
                info = self._tinfo[h]
                if x.dtype != info.dtype:
                    raise TypeError("kwargs[%s].dtype different from last time" % k)
                if x.device != info.device:
                    raise TypeError("kwargs[%s].device different from last time" % k)
                info.data_setter.set_value(x._dev_tensor())
                self._tensor_remaps[x] = CompiledTensorProxy(h)

    def _process_outputs(self, outputs):
        output_names = None
M
Megvii Engine Team 已提交
731
        if isinstance(outputs, collections.abc.Mapping):
M
Megvii Engine Team 已提交
732
            output_names, outputs = zip(*sorted(outputs.items()))
M
Megvii Engine Team 已提交
733
        elif not isinstance(outputs, collections.abc.Sequence):
M
Megvii Engine Team 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
            outputs = (outputs,)

        if not self._untraced:
            if output_names != self._output_names:
                too_many = set(output_names) - set(self._output_names)
                too_few = set(self._output_names) - set(output_names)
                if too_many:
                    raise TraceMismatchError(
                        "output has more keys than last time: %s" % " ".join(too_many)
                    )
                if too_few:
                    raise TraceMismatchError(
                        "output has less keys than last time: %s" % " ".join(too_few)
                    )
            if len(outputs) != len(self._output_bindings):
                raise TraceMismatchError("output size differs from last time")
        else:
            self._output_names = output_names
            self._output_bindings = []

        for i, x in enumerate(outputs):
            x = find_raw_tensor(x)
            if x is None:
                raise TypeError("every item of return value should be tensor")
            if self._untraced:
                if not isinstance(x, TraceMixin):
                    raise RuntimeError("output is not computed from inputs")
                h = x._TraceMixin__handle
                self._output_bindings.append(h)
            else:
                if not isinstance(x, CompiledTensorProxy):
                    raise RuntimeError("output is not computed from inputs")
                h = x._CompiledTensorProxy__handle
                if h != self._output_bindings[i]:
                    raise TraceMismatchError(
                        "retval[%s] is a different tensor than last time"
                        % (output_names and output_names[i] or i)
                    )
M
Megvii Engine Team 已提交
772

773 774 775 776 777 778 779 780 781 782
    def get_profile(self):
        """
        Get profiling result for compiled trace.

        :return: a json compatible object.
        """
        if not self._profiler:
            raise RuntimeError("trace is not set with profiling=True")
        return json.loads(self._profiler.get())

783 784 785 786 787 788
    def trace(self, *args, **kwargs):
        raise NotImplementedError(
            "trace is deemed unbeneficial with the new "
            "tracing mechanism. You should alwasy use __call__."
        )

M
Megvii Engine Team 已提交
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863

class CompiledTensorProxy(RawTensor):
    """
    Duck-typed RawTensor
    """

    def __init__(self, handle):
        self.__handle = handle
        self.__info = active_trace._tinfo[handle]
        self.__shape = None
        self.__data = None
        self.__value = None

    @property
    def dtype(self):
        return self.__info.varnode.dtype

    @property
    def device(self):
        return self.__info.varnode.device

    @property
    def shape(self):
        if self.__shape is None:
            if self.__info.shape_read:
                self.__shape = self.__info.shape_reader.get_value().shape
            elif self.__info.data_read:
                self.__shape = self._dev_tensor().shape
            else:
                raise TraceMismatchError("shape of this tensor is not read in trace")
        return self.__shape

    def numpy(self):
        if self.__value is None:
            if self.__info.value_read:
                self.__value = self.__info.value_reader.get_value()
            elif self.__info.data_read:
                self.__value = self._dev_tensor().numpy()
            else:
                raise TraceMismatchError("value of this tensor is not read in trace")
        return self.__value

    def _dev_tensor(self):
        if self.__data is None:
            if not self.__info.data_read:
                raise TraceMismatchError("raw data of this tensor is not read in trace")
            self.__data = self.__info.data_reader.get_value()
        return self.__data

    def __del__(self):
        if self.__info.shape_read and self.__shape is not None:
            self.__info.shape_reader.drop_value()
        if self.__info.value_read and self.__value is not None:
            self.__info.value_reader.drop_value()
        if self.__info.data_read and self.__data is not None:
            self.__info.data_reader.drop_value()


class LazyEvalTensor(RawTensor):
    def __init__(self, varnode):
        self.__varnode = varnode

    @property
    def dtype(self):
        return self.__varnode.dtype

    @property
    def device(self):
        return self.__varnode.device

    @property
    def shape(self):
        return self.__varnode.shape

    def numpy(self):
864
        return self.__varnode.value
M
Megvii Engine Team 已提交
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934

    def _dev_tensor(self):
        raise RuntimeError("cannot access data during symbolic tracing")


class TraceMixin:
    __subclass_cache = {}

    def __inject(self, handle):
        cache = __class__.__subclass_cache
        cls = self.__class__
        subcls = cache.get(cls)
        if subcls is None:
            subcls = cache[cls] = type("Traced" + cls.__name__, (__class__, cls), {})
        self.__class__ = subcls
        self.__handle = handle
        self.__cls = cls
        return self

    def __restore(self):
        cls = self.__cls
        del self.__handle
        del self.__cls
        self.__class__ = cls
        return self

    @property
    def shape(self):
        if not skip_tracing:
            active_trace._require_shape(self.__handle)
        return super().shape

    def numpy(self):
        if not skip_tracing:
            active_trace._require_value(self.__handle)
        return super().numpy()

    def _dev_tensor(self):
        if not skip_tracing:
            active_trace._require_data(self.__handle)
        return super()._dev_tensor()


class TracedRawTensor(TraceMixin, RawTensor):
    pass


class TracedLazyTensor(TraceMixin, LazyEvalTensor):
    pass


def assign_raw_tensor(lhs, rhs):
    handle = rhs._handle
    rhs.__dict__.clear()
    lhs.__dict__.clear()
    lhs.__class__ = RawTensor
    lhs.__init__(handle)


# this hook turns RawTensor into LazyEvalTensor
@apply.register()
def apply_symbolic_mode(op: OpDef, *args: RawTensor):
    graph = active_trace._lazy_eval_graph
    ivars = [
        getattr(x, "_LazyEvalTensor__varnode", None)
        or graph.make_const(x._dev_tensor())
        for x in args
    ]
    ovars = apply(op, *ivars)
    outputs = [LazyEvalTensor(v) for v in ovars]
935
    active_trace._lazy_eval_tensors.extend(weakref.ref(oup) for oup in outputs)
M
Megvii Engine Team 已提交
936 937 938 939 940 941
    return outputs


apply.disable(apply_symbolic_mode)


942 943 944 945
@apply.register()
def apply_const_symbolic_mode(op: Const, *args: RawTensor):
    graph = active_trace._lazy_eval_graph
    ret = LazyEvalTensor(graph.make_const(op.value, dtype=op.dtype, device=op.device))
946
    active_trace._lazy_eval_tensors.append(weakref.ref(ret))
947 948 949 950 951 952
    return (ret,)


apply.disable(apply_const_symbolic_mode)


M
Megvii Engine Team 已提交
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
@apply.register()
def apply_compiled_mode(op: OpDef, *args: RawTensor):
    if skip_tracing:
        args = [
            as_raw_tensor(x._dev_tensor()) if x.__class__ is CompiledTensorProxy else x
            for x in args
        ]
        return apply.super(op, *args)
    return active_trace._apply_op(op, args)


apply.disable(apply_compiled_mode)


# this hook injects TraceMixin
@apply.register()
def apply_with_tracing(op: OpDef, *args: RawTensor):
    outputs = apply.super(op, *args)
    active_trace._record_op(op, args, outputs)
    return outputs


apply.disable(apply_with_tracing)


978 979 980 981 982 983 984 985
@apply.register()
def apply_const_with_tracing(op: Const, *args: RawTensor):
    outputs = apply.super(op, *args)
    active_trace._record_const(op, outputs)
    return outputs


apply.disable(apply_const_with_tracing)
M
Megvii Engine Team 已提交
986 987 988 989 990 991 992 993


class BrokenRawTensor(RawTensor):
    def __getattribute__(self, _):
        raise RuntimeError("broken due to misuse of tracing")

    def __setattr__(self, *_):
        raise RuntimeError("broken due to misuse of tracing")
M
Megvii Engine Team 已提交
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017


@functools.singledispatch
def find_raw_tensor(x):
    return None


@find_raw_tensor.register(RawTensor)
def _(x):
    return x


@find_raw_tensor.register(TensorWrapperBase)
def _(x):
    x = getattr(x, "__wrapped__", None)
    if x is not None:
        return find_raw_tensor(x)


@find_raw_tensor.register(Tensor)
def _(x):
    x = getattr(x, "_data", None)
    if x is not None:
        return find_raw_tensor(x)