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 1.9 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from ..core._imperative_rt.core2 import pop_scope, push_scope
  2. class AutoNaming:
  3. r"""Name all executed operators automaticlly during tracing and record all tensors
  4. renamed by the user.
  5. """
  6. scopes = []
  7. c_ops = []
  8. name2ops = {}
  9. handle2names = {}
  10. __cls_attributes__ = {"scopes", "c_ops", "name2ops", "handle2names"}
  11. @classmethod
  12. def clear(cls):
  13. for attr in cls.__cls_attributes__:
  14. getattr(cls, attr).clear()
  15. @classmethod
  16. def push_scope(cls, scope):
  17. if scope is not None:
  18. push_scope(scope)
  19. cls.scopes.append(scope)
  20. @classmethod
  21. def pop_scope(cls):
  22. scope = cls.scopes.pop()
  23. if scope is not None:
  24. pop_scope(scope)
  25. @classmethod
  26. def get_scope(cls):
  27. return ".".join(s for s in cls.scopes if s is not None)
  28. @classmethod
  29. def gen_name(cls, x) -> str:
  30. scope = cls.get_scope()
  31. name = x.c_name if x.c_name else x._name
  32. return scope + "." + name if len(scope) else name
  33. @classmethod
  34. def record_var_name(cls, handle, name):
  35. cls.handle2names[handle] = name
  36. @classmethod
  37. def get_var_name(cls, handle):
  38. return cls.handle2names.pop(handle, None)
  39. @classmethod
  40. def record_opnode(cls, op):
  41. ops = cls.name2ops.get(op.name, [])
  42. if op not in ops:
  43. ops.append(op)
  44. cls.name2ops[op.name] = ops
  45. @classmethod
  46. def remove_duplicate_names(cls):
  47. for key, ops in cls.name2ops.items():
  48. if len(ops) == 1:
  49. continue
  50. for i, op in enumerate(ops):
  51. op.name = key + "[%s]" % str(i)
  52. if len(op.outputs) == 1:
  53. continue
  54. for var in op.outputs:
  55. var.name = var.name.replace(key, op.name)
  56. cls.name2ops.clear()