You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

naming.py 2.2 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. from ..core._imperative_rt.core2 import pop_scope, push_scope
  9. class AutoNaming:
  10. r"""Name all executed operators automaticlly during tracing and record all tensors
  11. renamed by the user.
  12. """
  13. scopes = []
  14. c_ops = []
  15. name2ops = {}
  16. handle2names = {}
  17. __cls_attributes__ = {"scopes", "c_ops", "name2ops", "handle2names"}
  18. @classmethod
  19. def clear(cls):
  20. for attr in cls.__cls_attributes__:
  21. getattr(cls, attr).clear()
  22. @classmethod
  23. def push_scope(cls, scope):
  24. if scope is not None:
  25. push_scope(scope)
  26. cls.scopes.append(scope)
  27. @classmethod
  28. def pop_scope(cls):
  29. scope = cls.scopes.pop()
  30. if scope is not None:
  31. pop_scope(scope)
  32. @classmethod
  33. def get_scope(cls):
  34. return ".".join(s for s in cls.scopes if s is not None)
  35. @classmethod
  36. def gen_name(cls, x) -> str:
  37. scope = cls.get_scope()
  38. name = x.c_name if x.c_name else x._name
  39. return scope + "." + name if len(scope) else name
  40. @classmethod
  41. def record_var_name(cls, handle, name):
  42. cls.handle2names[handle] = name
  43. @classmethod
  44. def get_var_name(cls, handle):
  45. return cls.handle2names.pop(handle, None)
  46. @classmethod
  47. def record_opnode(cls, op):
  48. ops = cls.name2ops.get(op.name, [])
  49. if op not in ops:
  50. ops.append(op)
  51. cls.name2ops[op.name] = ops
  52. @classmethod
  53. def remove_duplicate_names(cls):
  54. for key, ops in cls.name2ops.items():
  55. if len(ops) == 1:
  56. continue
  57. for i, op in enumerate(ops):
  58. op.name = key + "[%s]" % str(i)
  59. if len(op.outputs) == 1:
  60. continue
  61. for var in op.outputs:
  62. var.name = var.name.replace(key, op.name)
  63. cls.name2ops.clear()