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.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. @classmethod
  120. def register_as_builtin(cls, mod):
  121. assert issubclass(mod, Module)
  122. cls._opaque_types.add(mod)
  123. return mod
  124. @classmethod
  125. def is_builtin(cls, mod):
  126. return type(mod) in cls._opaque_types
  127. def push_scope(self, scope):
  128. self._active_scopes.append(scope)
  129. self.checker.push_scope()
  130. def pop_scope(self):
  131. self._active_scopes.pop()
  132. self.checker.pop_scope()
  133. def current_scope(self):
  134. if self._active_scopes:
  135. return self._active_scopes[-1]
  136. return None
  137. def top_scope(self):
  138. if self._active_scopes:
  139. return self._active_scopes[0]
  140. return None
  141. class NotExist:
  142. pass
  143. class PatchedFn:
  144. frame_dict = None
  145. name = None
  146. origin_fn = None
  147. def __init__(self, frame_dict, name):
  148. self.frame_dict = frame_dict
  149. self.name = name
  150. self.origin_fn = (
  151. self.frame_dict[name]
  152. if isinstance(frame_dict, collections.abc.Mapping)
  153. else getattr(frame_dict, name, NotExist)
  154. )
  155. def set_func(self, func):
  156. if isinstance(self.frame_dict, collections.abc.Mapping):
  157. self.frame_dict[self.name] = func
  158. else:
  159. if func is not NotExist:
  160. setattr(self.frame_dict, self.name, func)
  161. else:
  162. delattr(self.frame_dict, self.name)
  163. class Patcher:
  164. _builtin_functions = []
  165. _builtin_modules = [
  166. F,
  167. F.distributed,
  168. F.elemwise,
  169. F.inplace,
  170. F.loss,
  171. F.math,
  172. F.metric,
  173. F.nn,
  174. F.quantized,
  175. F.tensor,
  176. F.utils,
  177. F.vision,
  178. ]
  179. _builtin_methods = [
  180. Tensor,
  181. ArrayMethodMixin,
  182. ]
  183. def __init__(self, wrap_fn):
  184. self.patched_fn_ids = set()
  185. self.patched_fn = []
  186. self.visited_frames_ids = set()
  187. self.wrap_fn = wrap_fn
  188. for module in self._builtin_modules:
  189. self.patch_module(module)
  190. # some functions in F.nn are import from other module, and not in __all__
  191. self.auto_patch(F.nn.__dict__, False)
  192. for meth in BUILTIN_ARRAY_METHOD:
  193. self.patch_method(ArrayMethodMixin, meth, self.wrap_fn)
  194. self.patch_method(Tensor, "detach", self.wrap_fn)
  195. self.patch_method(Tensor, "__new__", self.wrap_fn)
  196. self.patch_method(QATModule, "_apply_fakequant_with_observer", self.wrap_fn)
  197. for i, j in self._builtin_functions:
  198. if id(i) not in self.visited_frames_ids:
  199. self.patch_function(i, j, self.wrap_fn)
  200. for m in module_tracer._opaque_types:
  201. self.auto_patch(getattr(getattr(m, "forward", m), "__globals__", {}))
  202. def patch_function(self, frame_dict, fn, wrap_fn):
  203. patched_fn = PatchedFn(frame_dict, fn)
  204. self.patched_fn_ids.add(id(patched_fn.origin_fn))
  205. patched_fn.set_func(wrap_fn(patched_fn.origin_fn))
  206. self.patched_fn.append(patched_fn)
  207. def patch_method(self, cls, name, wrap_fn):
  208. self.patch_function(cls, name, wrap_fn)
  209. def patch_cls(self, cls):
  210. import inspect
  211. if id(cls) not in self.visited_frames_ids:
  212. for k, v in cls.__dict__.items():
  213. if inspect.isfunction(v) and not k.startswith("_"):
  214. self.patch_function(cls, k, self.wrap_fn)
  215. self.visited_frames_ids.add(id(cls))
  216. def patch_module(self, module):
  217. import inspect
  218. if id(module.__dict__) not in self.visited_frames_ids:
  219. keys = (
  220. getattr(module, "__all__")
  221. if hasattr(module, "__all__")
  222. else module.__dict__.keys()
  223. )
  224. for k in keys:
  225. v = getattr(module, k)
  226. if inspect.isfunction(v) and not k.startswith("_"):
  227. self.patch_function(module.__dict__, k, self.wrap_fn)
  228. self.visited_frames_ids.add(id(module.__dict__))
  229. def auto_patch(self, frame_dict, check_frame_id=True):
  230. if id(frame_dict) not in self.visited_frames_ids or not check_frame_id:
  231. for k, v in frame_dict.items():
  232. if id(v) in self.patched_fn_ids:
  233. self.patch_function(frame_dict, k, self.wrap_fn)
  234. self.visited_frames_ids.add(id(frame_dict))
  235. def __enter__(self):
  236. return self
  237. def __exit__(self, type, vlaue, trace):
  238. while self.patched_fn:
  239. pf = self.patched_fn.pop()
  240. pf.set_func(pf.origin_fn)
  241. self.visited_frames_ids.clear()