naming.py 2.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2021 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.

from ..core._imperative_rt.core2 import pop_scope, push_scope


class AutoNaming:
    r"""
    Name all executed operators automaticlly during tracing and record all tensors
    renamed by the user.
    """

18 19 20 21 22
    scopes = []
    c_ops = []
    name2ops = {}
    handle2names = {}
    __cls_attributes__ = {"scopes", "c_ops", "name2ops", "handle2names"}
23

24 25 26 27
    @classmethod
    def clear(cls):
        for attr in cls.__cls_attributes__:
            getattr(cls, attr).clear()
28

29 30 31 32 33
    @classmethod
    def push_scope(cls, scope):
        if scope is not None:
            push_scope(scope)
        cls.scopes.append(scope)
34

35 36 37 38 39
    @classmethod
    def pop_scope(cls):
        scope = cls.scopes.pop()
        if scope is not None:
            pop_scope(scope)
40

41 42 43
    @classmethod
    def get_scope(cls):
        return ".".join(s for s in cls.scopes if s is not None)
44

45 46 47 48 49
    @classmethod
    def gen_name(cls, x) -> str:
        scope = cls.get_scope()
        name = x.c_name if x.c_name else x._name
        return scope + "." + name if len(scope) else name
50

51 52 53
    @classmethod
    def record_var_name(cls, handle, name):
        cls.handle2names[handle] = name
54

55 56 57
    @classmethod
    def get_var_name(cls, handle):
        return cls.handle2names.pop(handle, None)
58

59 60 61 62 63 64 65 66 67 68
    @classmethod
    def record_opnode(cls, op):
        ops = cls.name2ops.get(op.name, [])
        if op not in ops:
            ops.append(op)
        cls.name2ops[op.name] = ops

    @classmethod
    def remove_duplicate_names(cls):
        for key, ops in cls.name2ops.items():
69 70 71 72 73 74 75 76
            if len(ops) == 1:
                continue
            for i, op in enumerate(ops):
                op.name = key + "[%s]" % str(i)
                if len(op.outputs) == 1:
                    continue
                for var in op.outputs:
                    var.name = var.name.replace(key, op.name)
77
        cls.name2ops.clear()