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.

module_tracer.py 7.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. import collections
  9. from .. import Tensor
  10. from .. import functional as F
  11. from ..core.tensor.array_method import ArrayMethodMixin
  12. from ..module import Module
  13. from ..module.qat import QATModule
  14. from .checker import TracedModuleChecker
  15. _active_module_tracer = None
  16. BUILTIN_ARRAY_METHOD = [
  17. "__lt__",
  18. "__le__",
  19. "__gt__",
  20. "__ge__",
  21. "__eq__",
  22. "__ne__",
  23. "__neg__",
  24. "__pos__",
  25. "__abs__",
  26. "__invert__",
  27. "__round__",
  28. "__floor__",
  29. "__ceil__",
  30. "__add__",
  31. "__sub__",
  32. "__mul__",
  33. "__matmul__",
  34. "__truediv__",
  35. "__floordiv__",
  36. "__mod__",
  37. "__pow__",
  38. "__lshift__",
  39. "__rshift__",
  40. "__and__",
  41. "__or__",
  42. "__xor__",
  43. "__radd__",
  44. "__rsub__",
  45. "__rmul__",
  46. "__rmatmul__",
  47. "__rtruediv__",
  48. "__rfloordiv__",
  49. "__rmod__",
  50. "__rpow__",
  51. "__rlshift__",
  52. "__rrshift__",
  53. "__rand__",
  54. "__ror__",
  55. "__rxor__",
  56. "__iadd__",
  57. "__isub__",
  58. "__imul__",
  59. "__imatmul__",
  60. "__itruediv__",
  61. "__ifloordiv__",
  62. "__imod__",
  63. "__ipow__",
  64. "__ilshift__",
  65. "__irshift__",
  66. "__iand__",
  67. "__ior__",
  68. "__ixor__",
  69. "transpose",
  70. "astype",
  71. "reshape",
  72. "_broadcast",
  73. "flatten",
  74. "sum",
  75. "prod",
  76. "min",
  77. "max",
  78. "mean",
  79. "__getitem__",
  80. "__setitem__",
  81. ]
  82. BUILTIN_TENSOR_WRAP_METHOD = [
  83. "T",
  84. "to",
  85. "size",
  86. "shape",
  87. "detach",
  88. "device",
  89. "dtype",
  90. "grad",
  91. "item",
  92. "ndim",
  93. "numpy",
  94. "qparams",
  95. "set_value",
  96. "reset_zero",
  97. "requires_grad",
  98. "_reset",
  99. "_isscalar",
  100. "_setscalar",
  101. "_tuple_shape",
  102. "_unsetscalar",
  103. ]
  104. def get_tensor_wrapable_method():
  105. return BUILTIN_TENSOR_WRAP_METHOD + BUILTIN_ARRAY_METHOD
  106. def active_module_tracer():
  107. return _active_module_tracer
  108. def set_active_module_tracer(tracer):
  109. global _active_module_tracer
  110. _active_module_tracer = tracer
  111. class module_tracer:
  112. # builtin types
  113. _opaque_types = set()
  114. _active_scopes = None
  115. def __init__(self, wrap_fn):
  116. self._active_scopes = []
  117. self.checker = TracedModuleChecker(self)
  118. self.patcher = Patcher(wrap_fn)
  119. self._activate_constant_cache = []
  120. @classmethod
  121. def register_as_builtin(cls, mod):
  122. assert issubclass(mod, Module)
  123. cls._opaque_types.add(mod)
  124. return mod
  125. @classmethod
  126. def is_builtin(cls, mod):
  127. return type(mod) in cls._opaque_types
  128. def push_scope(self, scope):
  129. self._active_scopes.append(scope)
  130. self.checker.push_scope()
  131. self._activate_constant_cache.append([])
  132. def pop_scope(self):
  133. self._active_scopes.pop()
  134. self.checker.pop_scope()
  135. cache = self._activate_constant_cache.pop()
  136. for obj in cache:
  137. if hasattr(obj, "_NodeMixin__node"):
  138. delattr(obj, "_NodeMixin__node")
  139. def current_scope(self):
  140. if self._active_scopes:
  141. return self._active_scopes[-1]
  142. return None
  143. def current_constant_cache(self):
  144. if self._activate_constant_cache:
  145. return self._activate_constant_cache[-1]
  146. return None
  147. def top_scope(self):
  148. if self._active_scopes:
  149. return self._active_scopes[0]
  150. return None
  151. class NotExist:
  152. pass
  153. class PatchedFn:
  154. frame_dict = None
  155. name = None
  156. origin_fn = None
  157. def __init__(self, frame_dict, name):
  158. self.frame_dict = frame_dict
  159. self.name = name
  160. self.origin_fn = (
  161. self.frame_dict[name]
  162. if isinstance(frame_dict, collections.abc.Mapping)
  163. else getattr(frame_dict, name, NotExist)
  164. )
  165. def set_func(self, func):
  166. if isinstance(self.frame_dict, collections.abc.Mapping):
  167. self.frame_dict[self.name] = func
  168. else:
  169. if func is not NotExist:
  170. setattr(self.frame_dict, self.name, func)
  171. else:
  172. delattr(self.frame_dict, self.name)
  173. class Patcher:
  174. _builtin_functions = []
  175. _builtin_modules = [
  176. F,
  177. F.distributed,
  178. F.elemwise,
  179. F.inplace,
  180. F.loss,
  181. F.math,
  182. F.metric,
  183. F.nn,
  184. F.quantized,
  185. F.tensor,
  186. F.utils,
  187. F.vision,
  188. ]
  189. _builtin_methods = [
  190. Tensor,
  191. ArrayMethodMixin,
  192. ]
  193. def __init__(self, wrap_fn):
  194. self.patched_fn_ids = set()
  195. self.patched_fn = []
  196. self.visited_frames_ids = set()
  197. self.wrap_fn = wrap_fn
  198. for module in self._builtin_modules:
  199. self.patch_module(module)
  200. # some functions in F.nn are import from other module, and not in __all__
  201. self.auto_patch(F.nn.__dict__, False)
  202. for meth in BUILTIN_ARRAY_METHOD:
  203. self.patch_method(ArrayMethodMixin, meth, self.wrap_fn)
  204. self.patch_method(Tensor, "detach", self.wrap_fn)
  205. self.patch_method(Tensor, "__new__", self.wrap_fn)
  206. self.patch_method(QATModule, "_apply_fakequant_with_observer", self.wrap_fn)
  207. for i, j in self._builtin_functions:
  208. if id(i) not in self.visited_frames_ids:
  209. self.patch_function(i, j, self.wrap_fn)
  210. for m in module_tracer._opaque_types:
  211. self.auto_patch(getattr(getattr(m, "forward", m), "__globals__", {}))
  212. def patch_function(self, frame_dict, fn, wrap_fn):
  213. patched_fn = PatchedFn(frame_dict, fn)
  214. self.patched_fn_ids.add(id(patched_fn.origin_fn))
  215. patched_fn.set_func(wrap_fn(patched_fn.origin_fn))
  216. self.patched_fn.append(patched_fn)
  217. def patch_method(self, cls, name, wrap_fn):
  218. self.patch_function(cls, name, wrap_fn)
  219. def patch_cls(self, cls):
  220. import inspect
  221. if id(cls) not in self.visited_frames_ids:
  222. for k, v in cls.__dict__.items():
  223. if inspect.isfunction(v) and not k.startswith("_"):
  224. self.patch_function(cls, k, self.wrap_fn)
  225. self.visited_frames_ids.add(id(cls))
  226. def patch_module(self, module):
  227. import inspect
  228. if id(module.__dict__) not in self.visited_frames_ids:
  229. keys = (
  230. getattr(module, "__all__")
  231. if hasattr(module, "__all__")
  232. else module.__dict__.keys()
  233. )
  234. for k in keys:
  235. v = getattr(module, k)
  236. if inspect.isfunction(v) and not k.startswith("_"):
  237. self.patch_function(module.__dict__, k, self.wrap_fn)
  238. self.visited_frames_ids.add(id(module.__dict__))
  239. def auto_patch(self, frame_dict, check_frame_id=True):
  240. if id(frame_dict) not in self.visited_frames_ids or not check_frame_id:
  241. for k, v in frame_dict.items():
  242. if id(v) in self.patched_fn_ids:
  243. self.patch_function(frame_dict, k, self.wrap_fn)
  244. self.visited_frames_ids.add(id(frame_dict))
  245. def __enter__(self):
  246. return self
  247. def __exit__(self, type, vlaue, trace):
  248. while self.patched_fn:
  249. pf = self.patched_fn.pop()
  250. pf.set_func(pf.origin_fn)
  251. self.visited_frames_ids.clear()