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.

traced_module.py 86 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447
  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 builtins
  9. import collections
  10. import copy
  11. import fnmatch
  12. import functools
  13. import inspect
  14. import keyword
  15. import re
  16. import weakref
  17. from importlib import import_module
  18. from inspect import getcallargs, getmembers, isclass, ismethod
  19. from itertools import chain
  20. from types import FunctionType
  21. from typing import (
  22. Any,
  23. Callable,
  24. Dict,
  25. Iterable,
  26. List,
  27. Optional,
  28. Sequence,
  29. Tuple,
  30. Type,
  31. Union,
  32. )
  33. from .. import functional as F
  34. from .. import get_logger
  35. from .. import module as M
  36. from ..core._imperative_rt.core2 import Tensor as RawTensor
  37. from ..core._imperative_rt.core2 import (
  38. is_tracing_module,
  39. set_module_tracing,
  40. unset_module_tracing,
  41. )
  42. from ..core._trace_option import set_symbolic_shape
  43. from ..module import Module
  44. from ..module.qat import QATModule
  45. from ..quantization.fake_quant import LSQ, TQT, FakeQuantize, _FakeQuantize
  46. from ..quantization.observer import (
  47. ExponentialMovingAverageObserver,
  48. HistogramObserver,
  49. MinMaxObserver,
  50. Observer,
  51. PassiveObserver,
  52. SyncExponentialMovingAverageObserver,
  53. SyncMinMaxObserver,
  54. )
  55. from ..tensor import Tensor
  56. from ..version import __version__
  57. from .expr import (
  58. Apply,
  59. CallFunction,
  60. CallMethod,
  61. Constant,
  62. Expr,
  63. GetAttr,
  64. Input,
  65. get_suffix_name,
  66. is_apply_def,
  67. is_call_function,
  68. is_call_module,
  69. is_call_tensor_method,
  70. is_constant,
  71. is_getattr,
  72. is_input,
  73. )
  74. from .fake_quant import FakeQuantize as TM_FakeQuant
  75. from .module_tracer import (
  76. PatchedFn,
  77. Patcher,
  78. active_module_tracer,
  79. get_tensor_wrapable_method,
  80. module_tracer,
  81. set_active_module_tracer,
  82. )
  83. from .node import ModuleNode, Node, NodeMixin, TensorNode
  84. from .pytree import (
  85. USER_REGISTERED_CONTAINER_TYPE,
  86. USER_REGISTERED_LEAF_TYPE,
  87. ArgsIndex,
  88. TreeDef,
  89. _register_supported_type,
  90. tree_flatten,
  91. )
  92. from .serialization import (
  93. _ModuleState,
  94. load_apply_expr,
  95. load_call_module_expr,
  96. load_call_tensor_method_expr,
  97. load_functional,
  98. )
  99. from .utils import (
  100. _check_builtin_module_attr,
  101. _check_obj_attr,
  102. _convert_kwargs_to_args,
  103. replace_container_with_module_container,
  104. )
  105. logger = get_logger(__name__)
  106. def _is_builtin_name(name: str) -> bool:
  107. return (
  108. name in builtins.__dict__
  109. or name in keyword.kwlist
  110. or name in {"inf", "nan", "NoneType"}
  111. )
  112. def _is_leaf(node):
  113. assert isinstance(node, RawTensor), "doesn't support {} in return values".format(
  114. type(node)
  115. )
  116. return isinstance(node, RawTensor)
  117. _enable_graph_surgery_mode = False
  118. def _graph_surgery_mode():
  119. return _enable_graph_surgery_mode
  120. def _set_graph_surgery_mode(mode: bool):
  121. global _enable_graph_surgery_mode
  122. pre_mode = _enable_graph_surgery_mode
  123. _enable_graph_surgery_mode = mode
  124. return pre_mode
  125. def _node_to_tensor(*args, **kwargs):
  126. tensors = []
  127. nodes, tree_def = tree_flatten((args, kwargs))
  128. for n in nodes:
  129. if isinstance(n, TensorNode):
  130. if n.top_graph is not None:
  131. active_module_tracer().current_scope()._add_input(n)
  132. value = n.value
  133. if value is None:
  134. flag = _set_graph_surgery_mode(False)
  135. unset_module_tracing()
  136. value = F.zeros(shape=n._shape, dtype=n._dtype)
  137. set_module_tracing()
  138. _set_graph_surgery_mode(flag)
  139. orig_n = NodeMixin.get(value, None)
  140. if orig_n is None or "setitem" not in orig_n._name:
  141. NodeMixin.wrap_safe(value, n)
  142. tensors.append(value)
  143. else:
  144. tensors.append(n)
  145. tensors = tree_def.unflatten(tensors)
  146. return tensors
  147. def _tensor_to_node(tensors):
  148. if tensors is None:
  149. return None
  150. nodes = []
  151. tensors, out_def = tree_flatten(tensors)
  152. for t in tensors:
  153. if isinstance(t, Tensor):
  154. n = NodeMixin.get(t, None)
  155. if isinstance(n, TensorNode):
  156. n.value = t
  157. nodes.append(n)
  158. else:
  159. nodes.append(t)
  160. else:
  161. nodes.append(t)
  162. nodes = out_def.unflatten(nodes)
  163. return nodes
  164. def _wrap_method_to_tensor_node():
  165. def _any_method(name, func):
  166. def _any(*args, **kwargs):
  167. if is_tracing_module() and _graph_surgery_mode():
  168. args, kwargs = _node_to_tensor(*args, **kwargs)
  169. attr = getattr(args[0], name)
  170. outs = attr
  171. if callable(attr):
  172. outs = attr(*(args[1:]), **kwargs)
  173. if name == "__setitem__":
  174. _node_to_tensor(outs)
  175. return None
  176. outs = _tensor_to_node(outs)
  177. return outs
  178. else:
  179. outs = func
  180. if callable(func):
  181. outs = func(*args, **kwargs)
  182. if isinstance(func, property):
  183. outs = func.__get__(*args, **kwargs)
  184. return outs
  185. return _any
  186. tensor_method_patch = []
  187. for method in get_tensor_wrapable_method():
  188. patch = PatchedFn(TensorNode, method)
  189. if type(getattr(Tensor, method)) == property:
  190. patch.set_func(property(_any_method(method, patch.origin_fn)))
  191. else:
  192. patch.set_func(_any_method(method, patch.origin_fn))
  193. tensor_method_patch.append(patch)
  194. return tensor_method_patch
  195. def _convert_node_and_tensor(orig_func):
  196. @functools.wraps(orig_func)
  197. def _convert(*args, **kwargs):
  198. if is_tracing_module() and _graph_surgery_mode():
  199. args, kwargs = _node_to_tensor(*args, **kwargs)
  200. rst = orig_func(*args, **kwargs, method_func=_convert)
  201. rst = _tensor_to_node(rst)
  202. return rst
  203. else:
  204. rst = orig_func(*args, **kwargs)
  205. return rst
  206. return _convert
  207. def _wrap_mnode_getattr(orig_getattr):
  208. @functools.wraps(orig_getattr)
  209. def wraped_fn(self, name):
  210. if is_tracing_module() and _graph_surgery_mode():
  211. obj = self.owner
  212. current_graph = active_module_tracer().current_scope()
  213. if self.top_graph is not None:
  214. current_graph._add_input(self)
  215. attr = getattr(obj, name)
  216. node = attr
  217. if not isinstance(attr, TracedModuleBuilder):
  218. if isinstance(attr, Module):
  219. attr = TracedModuleBuilder(attr)
  220. setattr(obj, name, attr)
  221. if isinstance(attr, (NodeMixin, RawTensor)):
  222. NodeMixin.wrap(
  223. attr,
  224. lambda: GetAttr.make(
  225. self,
  226. type=NodeMixin.get_wrapped_type(attr),
  227. attr_name=name,
  228. name="",
  229. ),
  230. )
  231. if isinstance(attr, (NodeMixin, RawTensor)):
  232. node = NodeMixin.get(attr)
  233. if isinstance(node, ModuleNode) and isinstance(attr, (NodeMixin, Module)):
  234. node._owner = weakref.ref(attr)
  235. return node
  236. else:
  237. node = object.__getattribute__(self, name)
  238. return node
  239. return wraped_fn
  240. def _wrap_mnode_call(orig_call):
  241. @functools.wraps(orig_call)
  242. def wraped_fn(self, *args, **kwargs):
  243. if is_tracing_module() and _graph_surgery_mode():
  244. obj = self.owner
  245. if self.top_graph is not None:
  246. active_module_tracer().current_scope()._add_input(self)
  247. rst = obj(*args, **kwargs)
  248. else:
  249. raise TypeError("'ModuleNode' object is not callable")
  250. return rst
  251. return wraped_fn
  252. class _InsertExprs:
  253. def __init__(self, graph, expr: Optional[Expr] = None):
  254. self.graph = graph
  255. while graph.top_graph is not None:
  256. graph = graph.top_graph
  257. assert graph.inputs[0].owner._is_top
  258. self.root_graph = graph
  259. self.global_scope = InternalGraph(self.graph._name, self.graph._qualname)
  260. self.global_scope._namespace.merge(self.graph._namespace)
  261. self.expr = expr
  262. self._tensor_method_patch = None
  263. def __enter__(self):
  264. self.use_sym_shape = set_symbolic_shape(True)
  265. node_id, expr_id = self.root_graph._total_ids
  266. Node._set_next_id(node_id)
  267. Expr._set_next_id(expr_id)
  268. set_module_tracing()
  269. _set_graph_surgery_mode(True)
  270. assert active_module_tracer() is None
  271. set_active_module_tracer(
  272. module_tracer(lambda x: _convert_node_and_tensor(_wrapped_function(x)))
  273. )
  274. active_module_tracer().patcher.__enter__()
  275. for cls, name, func in [
  276. [ModuleNode, "__getattr__", _wrap_mnode_getattr],
  277. [ModuleNode, "__call__", _wrap_mnode_call],
  278. [TracedModuleBuilder, "__call__", _convert_node_and_tensor],
  279. ]:
  280. active_module_tracer().patcher.patch_function(cls, name, func)
  281. self._tensor_method_patch = _wrap_method_to_tensor_node()
  282. active_module_tracer().push_scope(self.global_scope)
  283. def __exit__(self, ty, va, tr):
  284. if va is not None:
  285. return False
  286. active_module_tracer().patcher.__exit__(ty, va, tr)
  287. while self._tensor_method_patch:
  288. pf = self._tensor_method_patch.pop()
  289. pf.set_func(pf.origin_fn)
  290. # delete ModuleNode.__call__ to avoid entering the
  291. # ModuleNode.__init__ method when call a ModuleNode object.
  292. delattr(ModuleNode, "__call__")
  293. module = self.graph.inputs[0].owner
  294. def build_traced_module(
  295. module: TracedModuleBuilder, target_module: TracedModule
  296. ):
  297. for k, v in module.__dict__.items():
  298. if isinstance(v, TracedModuleBuilder):
  299. traced_v = v.build()
  300. build_traced_module(v, traced_v)
  301. setattr(target_module, k, traced_v)
  302. build_traced_module(module, module)
  303. set_symbolic_shape(self.use_sym_shape)
  304. _set_graph_surgery_mode(False)
  305. set_active_module_tracer(None)
  306. unset_module_tracing()
  307. extra_inp_nodes = set(self.global_scope.inputs)
  308. max_inp_expr_idx = -1
  309. for node in extra_inp_nodes:
  310. assert (
  311. node.top_graph == self.graph
  312. ), "The input node ({}) is not in the graph ({})".format(node, self.graph)
  313. if isinstance(node, TensorNode) and node.expr in self.graph._exprs:
  314. max_inp_expr_idx = max(
  315. max_inp_expr_idx, self.graph._exprs.index(node.expr)
  316. )
  317. max_inp_expr_idx += 1
  318. insert_index = -1
  319. if self.expr is not None:
  320. insert_index = self.graph._exprs.index(self.expr)
  321. insert_index += 1
  322. if insert_index < max_inp_expr_idx:
  323. insert_index = max_inp_expr_idx
  324. for expr in self.global_scope._exprs:
  325. self.graph._exprs.insert(insert_index, expr)
  326. insert_index += 1
  327. self.graph._namespace.merge(self.global_scope._namespace)
  328. self.root_graph._total_ids = (Node._get_next_id(), Expr._get_next_id())
  329. self.root_graph.inputs[0].owner._update_ref()
  330. for node in self.root_graph.nodes():
  331. if isinstance(node, TensorNode):
  332. node.value = None
  333. return True
  334. class NameSpace:
  335. def __init__(self, name, qualname):
  336. self.name = name
  337. self.qualname = qualname
  338. self._used_names = {}
  339. def create_unique_name(self, name: str, node: Any = None) -> str:
  340. assert isinstance(name, str), "The name must be a string"
  341. if name in self._used_names and (self._used_names[name] is node):
  342. return name
  343. name = re.sub("[^0-9a-zA-Z_]+", "_", name)
  344. if name[0].isdigit():
  345. name = "_{}".format(name)
  346. while (
  347. name in self._used_names and self._used_names[name] is not None
  348. ) or _is_builtin_name(name):
  349. match = re.match(r"(.*)_(\d+)$", name)
  350. if match is None:
  351. name = name + "_1"
  352. else:
  353. base, num = match.group(1, 2)
  354. name = "{}_{}".format(base, int(num) + 1)
  355. self._used_names.setdefault(name)
  356. if node is not None:
  357. self.associate_name_with_obj(name, node)
  358. return name
  359. def auto_naming_for_outputs(self, expr: Expr):
  360. _add_suffix = lambda x: x + "_out"
  361. if is_call_module(expr):
  362. call_node = expr.inputs[0]
  363. qualname = "%s.[out]" % (call_node.qualname)
  364. name = call_node.name
  365. elif is_call_tensor_method(expr):
  366. name = expr.method.strip("_")
  367. qualname = "{}.[{}]".format(
  368. self.qualname, self.create_unique_name("method_%s" % (name)),
  369. )
  370. elif is_call_function(expr):
  371. name = expr.func.__name__
  372. qualname = "{}.[{}]".format(
  373. self.qualname, self.create_unique_name("func_%s" % name),
  374. )
  375. elif is_apply_def(expr):
  376. name = str(expr.opdef).lower()
  377. qualname = "{}.[{}]".format(
  378. self.qualname, self.create_unique_name("def_%s" % name),
  379. )
  380. elif is_getattr(expr):
  381. qualname = "{}.{}".format(expr.inputs[0].qualname, expr.name)
  382. name = get_suffix_name(self.qualname, qualname)
  383. _add_suffix = lambda x: x
  384. elif is_constant(expr) or is_input(expr):
  385. name = (
  386. expr.name if expr.name else "const_" + type(expr.value).__name__.lower()
  387. )
  388. qualname = "{}.[{}]".format(self.qualname, name)
  389. _add_suffix = lambda x: x
  390. for node in expr.outputs:
  391. cur_name = node._name if node._name else _add_suffix(name)
  392. node._name = self.create_unique_name(cur_name, node)
  393. if node._qualname == "":
  394. node._qualname = qualname
  395. assert get_suffix_name(self.qualname, qualname) is not None
  396. def merge(self, other: "NameSpace"):
  397. self._used_names.update(other.used_names)
  398. def associate_name_with_obj(self, name: str, node: Node):
  399. assert name in self.used_names
  400. assert self.used_names[name] is None, "The name(%s) is already in use" % (name)
  401. self._used_names[name] = node
  402. def unassociate_name_with_obj(self, node: Node):
  403. assert node.name in self.used_names
  404. # assert self.used_names[node.name] is node
  405. self._used_names[node.name] = None
  406. @property
  407. def used_names(self):
  408. return self._used_names
  409. class InternalGraph:
  410. r"""``InternalGraph`` is the main data structure used in the TracedModule.
  411. It is used to represent the execution procedure of Module's forward method.
  412. For example, the following code
  413. .. code-block::
  414. import megengine.random as rand
  415. import megengine.functional as F
  416. import megengine.module as M
  417. import megengine.traced_module as tm
  418. class MyModule(M.Module):
  419. def __init__(self):
  420. super().__init__()
  421. self.param = rand.normal(size=(3, 4))
  422. self.linear = M.Linear(4, 5)
  423. def forward(self, x):
  424. return F.relu(self.linear(x + self.param))
  425. net = MyModule()
  426. inp = F.zeros(shape = (3, 4))
  427. traced_module = tm.trace_module(net, inp)
  428. Will produce the following ``InternalGraph``::
  429. print(traced_module.graph)
  430. .. code-block:: text
  431. MyModule.Graph (self, x) {
  432. %2: linear = getattr(self, "linear") -> (Linear)
  433. %3: param = getattr(self, "param") -> (Tensor)
  434. %4: add_out = x.__add__(param, )
  435. %5: linear_out = linear(add_out, )
  436. %6: relu_out = nn.relu(linear_out, )
  437. return relu_out
  438. }
  439. """
  440. _exprs = None # type: List[Expr]
  441. _inputs = None # type: List[Node]
  442. _outputs = None # type: List[Node]
  443. _top_graph = None # type: InternalGraph
  444. _total_ids = None # type: List[int]
  445. def __init__(self, name: str, qualname: str):
  446. self._exprs = []
  447. self._inputs = []
  448. self._outputs = []
  449. self._watch_point = []
  450. self._end_point = []
  451. self._namespace = NameSpace(name, qualname)
  452. self._rst = collections.defaultdict(list)
  453. self._name = name
  454. self._qualname = qualname
  455. def _insert(self, expr):
  456. self._exprs.append(expr)
  457. @property
  458. def name(self) -> str:
  459. r"""Get the name of this graph."""
  460. return self._name
  461. @name.setter
  462. def name(self, new_name: str):
  463. r"""Set a new name to this graph."""
  464. mod = self.inputs[0].owner
  465. graph = self.top_graph
  466. assert graph is not None or mod._is_top, "The parent graph cannot be None."
  467. if graph is not None:
  468. assert graph._namespace.used_names.get(new_name, None) is None, (
  469. "The name(%s) is already in use. Please try a different one again."
  470. % (new_name)
  471. )
  472. new_name = graph._namespace.create_unique_name(new_name, self)
  473. self._name = new_name
  474. @property
  475. def qualname(self) -> str:
  476. r"""Get the `qualname` of this graph. The `qualname` can be used to get the
  477. submodule from the traced Module or Module.
  478. Example:
  479. .. code-block::
  480. import megengine.module as M
  481. import megengine.traced_module as tm
  482. import megengine as mge
  483. class block(M.Module):
  484. def __init__(self):
  485. super().__init__()
  486. self.relu = M.ReLU()
  487. def forward(self, x):
  488. return self.relu(x)
  489. class module(M.Module):
  490. def __init__(self):
  491. super().__init__()
  492. self.block = block()
  493. def forward(self, x):
  494. x = self.block(x)
  495. return x
  496. net = module()
  497. traced_net = tm.trace_module(net, mge.Tensor([0.]))
  498. qualname = traced_net.block.graph.qualname # qualname = "module.block"
  499. qualname = qualname.split(".", 1)[-1] # qualname = "block"
  500. assert qualname in list(map(lambda x: x[0], net.named_modules()))
  501. assert qualname in list(map(lambda x: x[0], traced_net.named_modules()))
  502. """
  503. return self._qualname
  504. @property
  505. def inputs(self) -> List[Node]:
  506. r"""Get the list of input Nodes of this graph.
  507. Returns:
  508. A list of ``Node``.
  509. """
  510. return self._inputs
  511. @property
  512. def outputs(self) -> List[Node]:
  513. r"""Get the list of output Nodes of this graph.
  514. Returns:
  515. A list of ``Node``.
  516. """
  517. return self._outputs
  518. @property
  519. def top_graph(self):
  520. r"""Get the parent graph of this graph.
  521. Returns:
  522. An ``InternalGraph``.
  523. """
  524. if self._top_graph:
  525. return self._top_graph()
  526. return None
  527. def exprs(self, recursive=True):
  528. r"""Get the Exprs that constitute this graph.
  529. Args:
  530. recursive: whether to get the Exprs in the subgraph.
  531. Default: True
  532. Returns:
  533. A ``ExprFilter`` containing all Exprs of this graph.
  534. """
  535. return ExprFilter(_expr_iter(self, recursive))
  536. def nodes(self, recursive=True):
  537. r"""Get the Nodes that constitute this graph.
  538. Args:
  539. recursive: whether to get the Nodes in the subgraph.
  540. Default: True
  541. Returns:
  542. A ``NodeFilter`` containing all Nodes of this graph.
  543. """
  544. return NodeFilter(_node_iter(self, recursive))
  545. def get_function_by_type(self, func: Callable = None, recursive=True):
  546. r"""Filter Exprs by the type of ``CallFunction``.
  547. Args:
  548. func: a built-in function, such as ``F.relu``.
  549. recursive: whether to get the Exprs in the subgraph.
  550. Default: True
  551. Returns:
  552. A :class:`~.TracedModule.ExprFilterCallFunction`.
  553. """
  554. return self.exprs(recursive).call_function(func)
  555. def get_method_by_type(self, method: str = None, recursive=True):
  556. r"""Filter Exprs by the type of ``CallMethod``.
  557. Args:
  558. method: a method string, such as "__add__".
  559. recursive: whether to get the Exprs in the subgraph.
  560. Default: True
  561. Returns:
  562. A :class:`~.TracedModule.ExprFilterCallMethod`.
  563. """
  564. return self.exprs(recursive).call_method(method)
  565. def get_expr_by_id(self, expr_id: List[int] = None, recursive=True):
  566. r"""Filter Exprs by their ``id``.
  567. Args:
  568. expr_id: a list of :class:`int`.
  569. recursive: whether to get the Exprs in the subgraph.
  570. Default: True
  571. Returns:
  572. A :class:`~.TracedModule.ExprFilterExprId`.
  573. """
  574. return self.exprs(recursive).expr_id(expr_id)
  575. def get_module_by_type(self, module_cls: Module, recursive=True):
  576. r"""Filter Nodes by the ``module_type`` of ``ModuleNode``.
  577. Args:
  578. module_cls: a subclass of :class:`~.Module`.
  579. recursive: whether to get the Nodes in the subgraph.
  580. Default: True
  581. Returns:
  582. A :class:`~.TracedModule.NodeFilterType`.
  583. """
  584. return self.nodes(recursive).type(module_cls)
  585. def get_node_by_id(self, node_id: List[int] = None, recursive=True):
  586. r"""Filter Nodes by their ``id``.
  587. The ``id`` of the ``Node`` can be obtained by the following code
  588. .. code-block::
  589. # node : Node
  590. print("{:i}".format(node))
  591. print(node.__format__("i"))
  592. # graph : InternalGraph
  593. print("{:i}".format(graph))
  594. print(graph.__format__("i"))
  595. Args:
  596. node_id: a list of :class:`int`.
  597. recursive: whether to get the Nodes in the subgraph.
  598. Default: True
  599. Returns:
  600. A :class:`~.TracedModule.NodeFilterNodeId`.
  601. """
  602. return self.nodes(recursive).node_id(node_id)
  603. def get_node_by_name(
  604. self, name: str = None, ignorecase: bool = True, recursive=True
  605. ):
  606. r"""Filter Nodes by their full name.
  607. The full name of the ``Node`` can be obtained by the following code
  608. .. code-block::
  609. # node : Node
  610. print("{:p}".format(node))
  611. print(node.__format__("p"))
  612. # graph : InternalGraph
  613. print("{:p}".format(graph))
  614. print(graph.__format__("p"))
  615. Args:
  616. name: a string in glob syntax that can contain ``?`` and
  617. ``*`` to match a single or arbitrary characters.
  618. ignorecase: whether to ignroe case.
  619. Default: True
  620. recursive: whether to get the Nodes in the subgraph.
  621. Default: True
  622. Returns:
  623. A :class:`~.TracedModule.NodeFilterName`.
  624. """
  625. return self.nodes(recursive).name(name, ignorecase)
  626. def _add_input(self, i):
  627. self._inputs.append(i)
  628. def _add_output(self, o):
  629. self._outputs.append(o)
  630. def get_dep_exprs(self, nodes: Sequence[Node]) -> List[Expr]:
  631. r"""Get the dependent Exprs of the ``nodes``.
  632. Args:
  633. nodes: a list of :class:`Node`.
  634. Returns:
  635. A list of dependent :class:`Expr`.
  636. """
  637. if not isinstance(nodes, Sequence):
  638. nodes = (nodes,)
  639. ret = list()
  640. queue = list(nodes)
  641. visited_queue = list()
  642. while queue:
  643. node = queue.pop()
  644. visited_queue.append(node)
  645. expr = node.expr
  646. if expr not in ret:
  647. ret.append(expr)
  648. for i in expr.inputs:
  649. if i not in queue and i not in visited_queue:
  650. queue.append(i)
  651. return ret
  652. def reset_inputs(self, *args, **kwargs):
  653. forma_mnode = self.inputs[0]
  654. moudle = forma_mnode.owner
  655. assert moudle._is_top, "reset_inputs only supports top graph"
  656. inputs, tree_def = tree_flatten(((moudle, *args), kwargs))
  657. def create_node(val: Tensor):
  658. name = self._namespace.create_unique_name("args")
  659. node = Input(
  660. type=TensorNode, name=name, qualname="%s.[%s]" % (self._qualname, name)
  661. ).outputs[0]
  662. self._namespace.associate_name_with_obj(node.name, node)
  663. node.shape = val.shape
  664. node.dtype = val.dtype
  665. return node
  666. formal_node_inputs = [
  667. forma_mnode,
  668. ]
  669. org_argdef = list(moudle.argdef_graph_map.keys())[0]
  670. for v in inputs[1:]:
  671. assert isinstance(v, RawTensor)
  672. formal_node_inputs.append(create_node(v))
  673. self._inputs[:] = formal_node_inputs
  674. moudle.argdef_graph_map[tree_def] = moudle.argdef_graph_map.pop(org_argdef)
  675. moudle.argdef_outdef_map[tree_def] = moudle.argdef_outdef_map.pop(org_argdef)
  676. return formal_node_inputs[1:]
  677. def add_input_node(
  678. self, shape: Tuple[int], dtype: str = "float32", name: str = "args"
  679. ):
  680. r"""Add an input node to the graph.
  681. The new Node will be the last of the positional arguments.
  682. Args:
  683. shape: the shape of the new input Node.
  684. dtype: the dtype of the new input Node.
  685. Default: float32
  686. name: the name of the new input Node. When the name is used in the graph,
  687. a suffix will be added to it.
  688. """
  689. forma_mnode = self.inputs[0]
  690. moudle = forma_mnode.owner
  691. assert moudle._is_top, "add_input_node only supports top graph"
  692. def create_node(name=None):
  693. name = self._namespace.create_unique_name(name)
  694. node = Input(
  695. type=TensorNode, name=name, qualname="%s.[%s]" % (self._qualname, name)
  696. ).outputs[0]
  697. self._namespace.associate_name_with_obj(node.name, node)
  698. node.shape = shape
  699. node.dtype = dtype
  700. return node
  701. org_argdef = list(moudle.argdef_graph_map.keys())[0]
  702. args, kwargs = org_argdef.unflatten(self._inputs)
  703. formal_inp_node = create_node(name)
  704. inputs, tree_def = tree_flatten(
  705. ((*args, formal_inp_node), kwargs),
  706. is_const_leaf=lambda x: not isinstance(x, (TensorNode, ModuleNode)),
  707. )
  708. self._inputs[:] = inputs[:]
  709. moudle.argdef_graph_map[tree_def] = moudle.argdef_graph_map.pop(org_argdef)
  710. moudle.argdef_outdef_map[tree_def] = moudle.argdef_outdef_map.pop(org_argdef)
  711. return formal_inp_node
  712. def reset_outputs(self, outputs):
  713. r"""Reset the output Nodes of the graph.
  714. .. note::
  715. This method only supports resetting the output of graphs
  716. that do not have a parent graph.
  717. Args:
  718. outputs: an object which inner element is Node. Support tuple, list
  719. dict, etc.
  720. For example, the following code
  721. .. code-block::
  722. import megengine.functional as F
  723. import megengine.module as M
  724. import megengine.traced_module as tm
  725. class MyModule(M.Module):
  726. def forward(self, x):
  727. x = x + 1
  728. return x
  729. net = MyModule()
  730. inp = F.zeros(shape = (1, ))
  731. traced_module = tm.trace_module(net, inp)
  732. graph = traced_module.graph
  733. inp_node = graph.inputs[1]
  734. out_node = graph.outputs[0]
  735. graph.reset_outputs((out_node, {"input": inp_node}))
  736. out = traced_module(inp)
  737. Will produce the following ``InternalGraph`` and ``out``::
  738. print(graph)
  739. print(out)
  740. .. code-block:: text
  741. MyModule.Graph (self, x) {
  742. %2: add_out = x.__add__(1, )
  743. return add_out, x
  744. }
  745. (Tensor([1.], device=xpux:0), {'input': Tensor([0.], device=xpux:0)})
  746. """
  747. outputs, out_def = tree_flatten(
  748. outputs, is_leaf=lambda x: isinstance(x, TensorNode),
  749. )
  750. forma_mnode = self.inputs[0]
  751. moudle = forma_mnode.owner
  752. assert moudle._is_top, "reset_outputs only supports top graph"
  753. tree_def = list(moudle.argdef_graph_map.keys())[0]
  754. self._outputs[:] = outputs
  755. moudle.argdef_outdef_map[tree_def] = out_def
  756. def add_output_node(self, node: TensorNode):
  757. r"""Add an output node to the Graph.
  758. The Graph output will become a ``tuple`` after calling ``add_output_node``.
  759. The first element of the ``tuple`` is the original output, and the second
  760. is the ``node``.
  761. For example, the following code
  762. .. code-block::
  763. import megengine.functional as F
  764. import megengine.module as M
  765. import megengine.traced_module as tm
  766. class MyModule(M.Module):
  767. def forward(self, x):
  768. x = x + 1
  769. return x
  770. net = MyModule()
  771. inp = F.zeros(shape = (1, ))
  772. traced_module = tm.trace_module(net, inp)
  773. graph = traced_module.graph
  774. inp_node = graph.inputs[1]
  775. out_node = graph.outputs[0]
  776. graph.add_output_node(inp_node)
  777. graph.add_output_node(out_node)
  778. out = traced_module(inp)
  779. Will produce the following ``InternalGraph`` and ``out``::
  780. print(graph)
  781. print(out)
  782. .. code-block:: text
  783. MyModule.Graph (self, x) {
  784. %2: add_out = x.__add__(1, )
  785. return add_out, x, add_out
  786. }
  787. ((Tensor([1.], device=xpux:0), Tensor([0.], device=xpux:0)), Tensor([1.], device=xpux:0))
  788. """
  789. forma_mnode = self.inputs[0]
  790. moudle = forma_mnode.owner
  791. assert moudle._is_top, "add_output_node only supports top graph"
  792. tree_def = list(moudle.argdef_graph_map.keys())[0]
  793. org_out_def = moudle.argdef_outdef_map[tree_def]
  794. org_outs = org_out_def.unflatten(self._outputs)
  795. outputs, out_def = tree_flatten(
  796. (org_outs, node), is_leaf=lambda x: isinstance(x, TensorNode),
  797. )
  798. self._outputs[:] = outputs
  799. moudle.argdef_outdef_map[tree_def] = out_def
  800. def insert_exprs(self, expr: Optional[Expr] = None):
  801. r"""Initialize the trace mode and insertion position.
  802. When used within a 'with' statement, this will temporary set the trace mode and
  803. then restore normal mode when the with statement exits::
  804. with graph.insert_exprs(e): # set the trace mode
  805. ... # trace function or module
  806. ... # inert exprs into graph and resotre normal mode
  807. Args:
  808. expr: the ``expr`` after which to insert. If None, the insertion position will be
  809. automatically set based on the input node.
  810. Returns:
  811. A resource manager that will initialize trace mode on ``__enter__`` and
  812. restore normal mode on ``__exit__``.
  813. """
  814. if expr is not None:
  815. assert expr.top_graph == self, "Expr to insert after is not in graph."
  816. return _InsertExprs(self, expr)
  817. def replace_node(self, repl_dict: Dict[Node, Node]):
  818. r"""Replace the Nodes in the graph.
  819. Args:
  820. repl_dict: the map {old_Node: new_Node} that specifies how to replace the Nodes.
  821. """
  822. while repl_dict:
  823. node, repl_node = repl_dict.popitem()
  824. assert type(node) == type(
  825. repl_node
  826. ), "The type of {}({}) and {}({}) are not the same".format(
  827. node, type(node).__name__, repl_node, type(repl_node).__name__
  828. )
  829. # check graph inputs and outputs
  830. for i, n in enumerate(self.outputs):
  831. if n is node:
  832. self.outputs[i] = repl_node
  833. # update users of node and repl_node
  834. # update inputs of expr in node.users
  835. graph = repl_node.top_graph
  836. assert graph is not None
  837. assert graph is self
  838. index = -1
  839. if not isinstance(repl_node.expr, Input):
  840. index = graph._exprs.index(repl_node.expr)
  841. dep_exprs = self.get_dep_exprs(repl_node)
  842. i = 0
  843. while i < len(node.users):
  844. n = node.users[i]
  845. if n in graph._exprs and index >= graph._exprs.index(n):
  846. i += 1
  847. continue
  848. if n in dep_exprs:
  849. logger.info("Find a loop: ignore this replacement once")
  850. logger.info("node: %s" % node.__repr__())
  851. logger.info("expr: %s" % n.__repr__())
  852. i += 1
  853. continue
  854. repl_node.users.append(n)
  855. node.users.pop(i)
  856. idx = n.inputs.index(node)
  857. n.inputs[idx] = repl_node
  858. def _merge_getattr_expr(self):
  859. getattr_nodes_map = dict() # Dcit[(Node, str), Node]
  860. node_to_attrname = dict() # Dict[Node, (Node, Str)]
  861. for expr in filter(lambda x: isinstance(x, GetAttr), self._exprs):
  862. base_node, attr_name = expr.inputs[0], expr.name
  863. if expr.inputs[0] in node_to_attrname:
  864. base_node, base_name = node_to_attrname[expr.inputs[0]]
  865. attr_name = "{}.{}".format(base_name, expr.name)
  866. if get_suffix_name(self.qualname, expr.outputs[0].qualname) != attr_name:
  867. expected_qualname = base_node.qualname + "." + attr_name
  868. logger.warning(
  869. "{}.qualname expects {}, got {} actually. You can re-trace this "
  870. "TracedModel to make the name correct.".format(
  871. expr.outputs[0], expected_qualname, expr.outputs[0].qualname
  872. )
  873. )
  874. expr.outputs[0]._qualname = expected_qualname
  875. key = (base_node, attr_name)
  876. node_to_attrname[expr.outputs[0]] = key
  877. if key in getattr_nodes_map:
  878. existed_node = getattr_nodes_map[key]
  879. repl_node = expr.outputs[0]
  880. for expr in repl_node.users:
  881. existed_node.users.append(expr)
  882. idx = expr.inputs.index(repl_node)
  883. expr.inputs[idx] = existed_node
  884. repl_node.users = []
  885. else:
  886. if attr_name != expr.name:
  887. expr.name = attr_name
  888. expr.inputs[0].users.remove(expr)
  889. self.inputs[0].users.append(expr)
  890. expr.inputs[0] = self.inputs[0]
  891. getattr_nodes_map[key] = expr.outputs[0]
  892. def compile(self):
  893. r"""Delete unused expr."""
  894. self._merge_getattr_expr()
  895. dep_exprs = self.get_dep_exprs(self.outputs)
  896. i = 0
  897. while i < len(self._exprs):
  898. expr = self._exprs[i]
  899. if expr in dep_exprs or expr._disable_remove:
  900. i += 1
  901. continue
  902. for n in expr.inputs:
  903. n.users.remove(expr)
  904. self._exprs.remove(expr)
  905. for n in expr.outputs:
  906. self._namespace.unassociate_name_with_obj(n)
  907. def _reset_ids(self):
  908. for total_expr_id, expr in enumerate(self.exprs()):
  909. expr._id = total_expr_id
  910. for total_node_id, node in enumerate(self.nodes()):
  911. node._id = total_node_id
  912. self._total_ids = (total_node_id + 1, total_expr_id + 1)
  913. def _re_associate_name(self):
  914. self._namespace.used_names.clear()
  915. for node in self.nodes(False):
  916. node._name = self._namespace.create_unique_name(node.name, node)
  917. def interpret(self, *inputs):
  918. node2value = {}
  919. end_nodes_set = set(self._end_point)
  920. endnode2value = {}
  921. def get_all_endnode_val(n, v):
  922. if n in end_nodes_set:
  923. endnode2value[n] = v
  924. end_nodes_set.remove(n)
  925. return not end_nodes_set
  926. return False
  927. ref_count = lambda n: len(n.users) + (1 if n in self._outputs else 0)
  928. for n, v in zip(self._inputs, inputs):
  929. if ref_count(n) > 0:
  930. node2value[n] = [v, ref_count(n)]
  931. if n in self._watch_point:
  932. self._rst[n].append(v)
  933. if n in self._end_point and get_all_endnode_val(n, v):
  934. return list(endnode2value[i] for i in self._end_point)
  935. for expr in self._exprs:
  936. values = expr.interpret(*list(node2value[i][0] for i in expr.inputs))
  937. for n in expr.inputs:
  938. node2value[n][1] -= 1
  939. if node2value[n][1] == 0:
  940. node2value.pop(n)
  941. if values is not None:
  942. assert len(values) == len(expr.outputs)
  943. for n, v in zip(expr.outputs, values):
  944. if ref_count(n) > 0:
  945. node2value[n] = [v, ref_count(n)]
  946. if n in self._watch_point:
  947. self._rst[n] = v
  948. if self._end_point and get_all_endnode_val(n, v):
  949. return list(endnode2value[i] for i in self._end_point)
  950. return list(node2value[i][0] for i in self._outputs)
  951. def eval(self, *inputs: Tuple[Tensor]):
  952. r"""Call this method to execute the graph.
  953. Args:
  954. inputs: the tensors corresponding to the ``graph.inputs[1:]``.
  955. """
  956. assert len(inputs) == len(self._inputs) - 1
  957. inp = [self._inputs[0].owner] + list(inputs)
  958. return self.interpret(*inp)
  959. def __repr__(self):
  960. return self.__format__()
  961. def __format__(self, format_spec: str = "") -> str:
  962. saved_format_spec = Node._set_format_spec(format_spec)
  963. name = ""
  964. if self._name:
  965. name = "%s.Graph" % self._name
  966. res = "{} ({}) {{\n\t{}\n\treturn {}\n}}".format(
  967. name,
  968. ", ".join(str(i) for i in self._inputs),
  969. "\n\t".join("{}".format(str(i)) for i in self._exprs),
  970. ", ".join(str(i) for i in self._outputs),
  971. )
  972. Node._set_format_spec(saved_format_spec)
  973. return res
  974. def __getstate__(self):
  975. state = {
  976. "_exprs": self._exprs,
  977. "_inputs": self._inputs,
  978. "_outputs": self._outputs,
  979. "_watch_point": [],
  980. "_end_point": [],
  981. "_namespace": self._namespace,
  982. "_rst": collections.defaultdict(list),
  983. "_name": self._name,
  984. "_qualname": self._qualname,
  985. }
  986. if self._total_ids:
  987. state["_total_ids"] = self._total_ids
  988. _check_obj_attr(state)
  989. return state
  990. def __setstate__(self, state):
  991. old_version = False
  992. if "_module_name" in state:
  993. old_version = True
  994. state["_qualname"] = state.pop("_module_name")
  995. prefix_name = state.pop("_prefix_name")
  996. if prefix_name:
  997. state["_name"] = "{}_{}".format(prefix_name, state["_name"])
  998. self.__dict__.update(state)
  999. if old_version:
  1000. self.inputs[0]._qualname = self._qualname
  1001. for e in self.exprs(False):
  1002. if isinstance(e, GetAttr):
  1003. e.outputs[0]._qualname = "{}.{}".format(
  1004. e.inputs[0]._qualname, e.name
  1005. )
  1006. for n in self.nodes(False):
  1007. if isinstance(n.expr, CallMethod) and isinstance(
  1008. n.expr.inputs[0], ModuleNode
  1009. ):
  1010. n._qualname = n.expr.inputs[0]._qualname + ".[out]"
  1011. continue
  1012. if (
  1013. not isinstance(n.expr, GetAttr)
  1014. and isinstance(n, TensorNode)
  1015. and n._qualname
  1016. ):
  1017. n._qualname = "{}.{}".format(self._qualname, n._qualname)
  1018. self._namespace = NameSpace(self._name, self._qualname)
  1019. self._re_associate_name()
  1020. def __copy__(self):
  1021. cls = self.__class__
  1022. result = cls.__new__(cls)
  1023. result.__dict__.update(self.__dict__)
  1024. return result
  1025. def __deepcopy__(self, memo):
  1026. if id(self) in memo:
  1027. return memo[id(self)]
  1028. cls = self.__class__
  1029. result = cls.__new__(cls)
  1030. state = {}
  1031. memo[id(self)] = result
  1032. for k, v in self.__dict__.items():
  1033. if not isinstance(v, weakref.ReferenceType):
  1034. state[k] = copy.deepcopy(v, memo)
  1035. result.__dict__.update(state)
  1036. return result
  1037. def _get_meth_name(obj, func):
  1038. tp = obj if isinstance(obj, type) else type(obj)
  1039. for cls in tp.mro():
  1040. for k, v in cls.__dict__.items():
  1041. if v == func:
  1042. return k
  1043. return None
  1044. def _wrapped_function(orig_func):
  1045. @functools.wraps(orig_func)
  1046. def wrapped_fn(*args, **kwargs):
  1047. method_func = kwargs.pop("method_func", wrapped_fn)
  1048. if is_tracing_module():
  1049. unset_module_tracing()
  1050. inputs, tree_def = tree_flatten((args, kwargs))
  1051. for i in inputs:
  1052. if not NodeMixin.get(i, None):
  1053. if isinstance(i, (RawTensor, NodeMixin)):
  1054. NodeMixin.wrap_safe(i, Constant.make(i))
  1055. args, kwargs = _convert_kwargs_to_args(orig_func, args, kwargs)
  1056. meth_name = _get_meth_name(args[0], method_func)
  1057. arg_type = args[0] if isinstance(args[0], type) else type(args[0])
  1058. if meth_name and arg_type and issubclass(arg_type, RawTensor):
  1059. inputs, tree_def = tree_flatten((args, kwargs))
  1060. self = inputs[0]
  1061. if meth_name == "__new__":
  1062. if all([not isinstance(i, RawTensor) for i in inputs]):
  1063. # only trace Tensor.__new__() when there are tensors in args
  1064. set_module_tracing()
  1065. return orig_func(*args, **kwargs)
  1066. if isinstance(args[1], RawTensor):
  1067. node = NodeMixin.get(inputs[1])
  1068. inputs[1] = copy.copy(inputs[1])
  1069. # copy inputs[1] to avoid tensor and Tensor(tensor) share same m_tensor,
  1070. # which will cause they have same _NodeMixin__node in tracing.
  1071. NodeMixin.wrap_safe(inputs[1], node)
  1072. args, kwargs = tree_def.unflatten(inputs)
  1073. call_node = CallMethod.make(self, meth_name)
  1074. else:
  1075. call_node = CallMethod.make(NodeMixin.get(self), meth_name)
  1076. call_node.add_inputs(inputs[1:])
  1077. else:
  1078. inputs, tree_def = tree_flatten((args, kwargs))
  1079. call_node = CallFunction.make(orig_func)
  1080. call_node.add_inputs(inputs)
  1081. call_node.arg_def = tree_def
  1082. rst = orig_func(*args, **kwargs)
  1083. if meth_name == "__setitem__":
  1084. rst = self
  1085. if rst is not None:
  1086. outputs, out_def = tree_flatten(rst, is_leaf=_is_leaf)
  1087. call_node.out_def = out_def
  1088. else:
  1089. outputs = None
  1090. call_node.add_outputs(outputs)
  1091. set_module_tracing()
  1092. return rst
  1093. return orig_func(*args, **kwargs)
  1094. return wrapped_fn
  1095. class TracedModuleBuilder(NodeMixin):
  1096. _mod = None # type: Module
  1097. _body = None # type: InternalGraph
  1098. _is_builtin = None # type: bool
  1099. _argdef_graph_map = None # type: Dict[Treedef, "InternalGraph"]
  1100. _argdef_outdef_map = None # type: Dict[Treedef, Treedef]
  1101. nodes = None
  1102. __builder_attributes__ = [
  1103. "_mod",
  1104. "_body",
  1105. "_NodeMixin__node",
  1106. "_is_builtin",
  1107. "build",
  1108. "_record_wrapped_nodes",
  1109. "_argdef_graph_map",
  1110. "_argdef_outdef_map",
  1111. "_check_qat_module",
  1112. "nodes",
  1113. "__class__",
  1114. "__dict__",
  1115. "_is_top",
  1116. ]
  1117. def __init__(self, mod, is_top_module=False):
  1118. super(TracedModuleBuilder, self).__init__()
  1119. assert isinstance(mod, Module)
  1120. self._mod = mod
  1121. self._body = None
  1122. self._is_top = is_top_module
  1123. self._is_builtin = (
  1124. True
  1125. if isinstance(mod, (Observer, _FakeQuantize))
  1126. else module_tracer.is_builtin(mod)
  1127. )
  1128. if isinstance(self._mod, QATModule):
  1129. unset_module_tracing()
  1130. self._check_qat_module(self._mod)
  1131. set_module_tracing()
  1132. self._argdef_graph_map = {}
  1133. self._argdef_outdef_map = {}
  1134. self.nodes = set()
  1135. # The builder will be passed to self._mod.forward as 'self' argument. If the 'forward' uses super().xxx to call method of its base classes, the trace procedure will throw exceprion, because the builder doesn't inherit from self._mod.__bases__.
  1136. # modify self.__class__ and let the builder inherit from TracedModuleBuilder and mod.__class__.
  1137. self.__class__ = type(
  1138. "TracedModuleBuilder",
  1139. (TracedModuleBuilder, mod.__class__),
  1140. dict(TracedModuleBuilder.__dict__),
  1141. )
  1142. def _check_qat_module(self, qat_module):
  1143. def isbuiltin(m):
  1144. return m is None or module_tracer.is_builtin(m)
  1145. if qat_module.with_act:
  1146. act_observer = qat_module.act_observer
  1147. act_fakequant = qat_module.act_fake_quant
  1148. if not isbuiltin(act_observer) or not isbuiltin(act_fakequant):
  1149. qparams = (
  1150. act_observer.get_qparams()
  1151. if hasattr(act_observer, "get_qparams")
  1152. else act_fakequant.get_qparams()
  1153. )
  1154. dtype = (
  1155. act_observer.dtype
  1156. if hasattr(act_observer, "dtype")
  1157. else act_fakequant.dtype
  1158. )
  1159. qat_module.act_observer = None
  1160. qat_module.act_fake_quant = TM_FakeQuant(dtype)
  1161. qat_module.act_fake_quant.set_qparams(qparams)
  1162. if qat_module.with_weight:
  1163. weight_observer = qat_module.weight_observer
  1164. weight_fakequant = qat_module.weight_fake_quant
  1165. if not isbuiltin(weight_observer) or not isbuiltin(weight_fakequant):
  1166. qparams = (
  1167. weight_observer.get_qparams()
  1168. if hasattr(weight_observer, "get_qparams")
  1169. else weight_fakequant.get_qparams()
  1170. )
  1171. dtype = (
  1172. weight_observer.dtype
  1173. if hasattr(weight_observer, "dtype")
  1174. else weight_fakequant.dtype
  1175. )
  1176. qat_module.weight_observer = None
  1177. qat_module.weight_fake_quant = TM_FakeQuant(dtype)
  1178. qat_module.weight_fake_quant.set_qparams(qparams)
  1179. def build(self):
  1180. if self._is_builtin:
  1181. assert module_tracer.is_builtin(self._mod)
  1182. mod_type = type(self._mod)
  1183. for node in self.nodes:
  1184. node.module_type = mod_type
  1185. return self._mod
  1186. elif isinstance(self._mod, TracedModule) and _graph_surgery_mode():
  1187. return self._mod
  1188. else:
  1189. is_qat = isinstance(self._mod, QATModule) or (
  1190. isinstance(self._mod, TracedModule) and self._mod.is_qat
  1191. )
  1192. traced_module = TracedModule(
  1193. self._is_top, self._argdef_graph_map, self._argdef_outdef_map, is_qat
  1194. )
  1195. for _, g in self._argdef_graph_map.items():
  1196. g.compile()
  1197. if self._is_top:
  1198. g._total_ids = (Node._get_next_id(), Expr._get_next_id())
  1199. for k, v in self.__dict__.items():
  1200. if k not in TracedModuleBuilder.__builder_attributes__:
  1201. if isinstance(v, TracedModuleBuilder):
  1202. v = v.build()
  1203. setattr(traced_module, k, v)
  1204. elif isinstance(v, RawTensor):
  1205. setattr(traced_module, k, v)
  1206. if isinstance(self._mod, QATModule):
  1207. unset_module_tracing()
  1208. traced_module.with_act = self._mod.with_act
  1209. traced_module.with_weight = self._mod.with_weight
  1210. if not hasattr(traced_module, "act_fake_quant"):
  1211. traced_module.act_fake_quant = None
  1212. if not hasattr(traced_module, "act_observer"):
  1213. traced_module.act_observer = None
  1214. if not hasattr(traced_module, "weight_fake_quant"):
  1215. traced_module.weight_fake_quant = None
  1216. if not hasattr(traced_module, "weight_observer"):
  1217. traced_module.weight_observer = None
  1218. set_module_tracing()
  1219. if self._is_top:
  1220. traced_module._update_ref()
  1221. return traced_module
  1222. def _record_wrapped_nodes(self, node):
  1223. self.nodes.add(node)
  1224. def __call__(self, *args, **kwargs):
  1225. assert isinstance(self._mod, Module)
  1226. is_graph_surgery_mode = _graph_surgery_mode()
  1227. if isinstance(self._mod, TracedModule) and is_graph_surgery_mode:
  1228. _set_graph_surgery_mode(False)
  1229. # prepare args and kwargs for inner graph
  1230. if "method_func" in kwargs:
  1231. kwargs.pop("method_func")
  1232. args, kwargs = _convert_kwargs_to_args(self._mod.forward, args, kwargs, True)
  1233. def mark_constant(x):
  1234. node = NodeMixin.get(x, None)
  1235. if node is None: # capture as constant
  1236. NodeMixin.wrap(x, lambda: Constant.make(x))
  1237. inputs, tree_def = tree_flatten(((self, *args), kwargs))
  1238. for i in inputs:
  1239. mark_constant(i)
  1240. callnode = CallMethod.make(NodeMixin.get(self))
  1241. callnode.add_inputs(inputs[1:])
  1242. callnode.arg_def = tree_def
  1243. if self._is_builtin or tree_def in self._argdef_graph_map:
  1244. unset_module_tracing()
  1245. rst = self._mod(*args, **kwargs)
  1246. outputs, out_def = tree_flatten(rst, is_leaf=_is_leaf)
  1247. set_module_tracing()
  1248. if self._is_builtin:
  1249. self._body = None
  1250. elif tree_def in self._argdef_graph_map:
  1251. self._body = self._argdef_graph_map[tree_def]
  1252. else:
  1253. orig_self = NodeMixin.get(self)
  1254. parent_graph = active_module_tracer().current_scope()
  1255. module_qualname = orig_self._qualname
  1256. self._body = InternalGraph(
  1257. name=parent_graph._namespace.create_unique_name(module_qualname),
  1258. qualname=module_qualname,
  1259. )
  1260. parent_graph._namespace.associate_name_with_obj(self._body.name, self._body)
  1261. active_module_tracer().push_scope(self._body)
  1262. # rebind self to new input node
  1263. NodeMixin.wrap_safe(
  1264. self,
  1265. Input.make(
  1266. name="self",
  1267. qualname=module_qualname,
  1268. type=NodeMixin.get_wrapped_type(self),
  1269. ),
  1270. )
  1271. origin_inp_node = [NodeMixin.get(i, None) for i in inputs[1:]]
  1272. # prepare args and kwargs for inner graph
  1273. index_args, index_kwargs = tree_def.unflatten(
  1274. [
  1275. ArgsIndex(0),
  1276. *list(ArgsIndex(i + 1) for i in range(len(origin_inp_node))),
  1277. ]
  1278. )
  1279. key2idx = getcallargs(type(self._mod).forward, *index_args, **index_kwargs)
  1280. idx2key = {}
  1281. for k, v in key2idx.items():
  1282. if isinstance(v, ArgsIndex):
  1283. idx2key[v.index] = k
  1284. else:
  1285. flatten_argidx, _ = tree_flatten(v)
  1286. for _i, v in enumerate(flatten_argidx):
  1287. if isinstance(v, ArgsIndex):
  1288. idx2key[v.index] = k + "_%d" % _i
  1289. def wrap(x, name):
  1290. if isinstance(x, (RawTensor, NodeMixin)):
  1291. NodeMixin.wrap(
  1292. x,
  1293. lambda: Input.make(
  1294. type=NodeMixin.get_wrapped_type(x),
  1295. name=name,
  1296. qualname="%s.[%s]" % (module_qualname, name),
  1297. ),
  1298. )
  1299. return x
  1300. args = [self]
  1301. orig_traced_inputs = (
  1302. None
  1303. if not isinstance(self._mod, TracedModule)
  1304. else self._mod.argdef_graph_map[tree_def].inputs
  1305. )
  1306. ind = 1
  1307. for v in inputs[1:]:
  1308. if isinstance(v, (RawTensor, NodeMixin)):
  1309. args_name = (
  1310. orig_traced_inputs[ind]._name
  1311. if orig_traced_inputs
  1312. else idx2key[ind]
  1313. )
  1314. ind += 1
  1315. args.append(wrap(v, args_name))
  1316. else:
  1317. args.append(v)
  1318. args, kwargs = tree_def.unflatten(args)
  1319. active_module_tracer().patcher.auto_patch(
  1320. getattr(getattr(self._mod, "forward", self._mod), "__globals__", {})
  1321. )
  1322. rst = type(self._mod).forward(*args, **kwargs)
  1323. if _graph_surgery_mode():
  1324. rst = _node_to_tensor(rst)[0][0]
  1325. outputs, out_def = tree_flatten(rst, is_leaf=_is_leaf)
  1326. for i in (
  1327. outputs if isinstance(outputs, collections.abc.Sequence) else (outputs,)
  1328. ):
  1329. mark_constant(i)
  1330. active_module_tracer().current_scope()._add_output(NodeMixin.get(i))
  1331. NodeMixin.wrap_safe(self, orig_self)
  1332. for arg, node in zip(inputs[1:], origin_inp_node):
  1333. if node:
  1334. NodeMixin.wrap_safe(arg, node)
  1335. active_module_tracer().pop_scope()
  1336. # rebind output to outer graph
  1337. callnode.out_def = out_def
  1338. callnode.add_outputs(outputs)
  1339. self._argdef_graph_map[callnode.arg_def] = self._body
  1340. self._argdef_outdef_map[callnode.arg_def] = out_def
  1341. _set_graph_surgery_mode(is_graph_surgery_mode)
  1342. return rst
  1343. def __setattr__(self, name, value):
  1344. object.__setattr__(self, name, value)
  1345. def __repr__(self):
  1346. return repr(self._mod)
  1347. def __getattr__(self, name):
  1348. if name not in self._mod.__dict__:
  1349. attr = getattr(type(self._mod), name).__get__(self, type(self))
  1350. else:
  1351. attr = getattr(self._mod, name)
  1352. if (
  1353. isinstance(attr, FunctionType)
  1354. and id(attr) in active_module_tracer().patcher.patched_fn_ids
  1355. ):
  1356. return active_module_tracer().patcher.wrap_fn(attr)
  1357. if isinstance(attr, (List, Dict)):
  1358. flag = _set_graph_surgery_mode(False)
  1359. unset_module_tracing()
  1360. has_module, m_container = replace_container_with_module_container(attr)
  1361. if m_container:
  1362. attr = m_container
  1363. if has_module and not m_container:
  1364. raise ValueError(
  1365. "Can not trace the module that uses the same container to store"
  1366. " Module and Non-Module objects."
  1367. )
  1368. set_module_tracing()
  1369. _set_graph_surgery_mode(flag)
  1370. if isinstance(attr, Module):
  1371. attr = TracedModuleBuilder(attr)
  1372. if isinstance(attr, (Module, RawTensor)):
  1373. setattr(self, name, attr)
  1374. NodeMixin.wrap(
  1375. attr,
  1376. lambda: GetAttr.make(
  1377. NodeMixin.get(self),
  1378. type=NodeMixin.get_wrapped_type(attr),
  1379. attr_name=name,
  1380. name="",
  1381. ),
  1382. )
  1383. return attr
  1384. def __getattribute__(self, name):
  1385. if name in TracedModuleBuilder.__builder_attributes__:
  1386. return object.__getattribute__(self, name)
  1387. else:
  1388. wrapped = object.__getattribute__(self, name)
  1389. class_members = dict(inspect.getmembers(self.__class__))
  1390. if name in self._mod.__dict__:
  1391. mod_attr = getattr(self._mod, name)
  1392. if name in class_members:
  1393. if (
  1394. not isinstance(wrapped, TracedModuleBuilder)
  1395. and wrapped is not mod_attr
  1396. ):
  1397. wrapped = self.__getattr__(name)
  1398. if isinstance(wrapped, TracedModuleBuilder):
  1399. if not isinstance(mod_attr, (List, Dict, QATModule)):
  1400. assert mod_attr is wrapped._mod
  1401. else:
  1402. assert mod_attr is wrapped
  1403. if isinstance(wrapped, (NodeMixin, RawTensor)):
  1404. NodeMixin.wrap(
  1405. wrapped,
  1406. lambda: GetAttr.make(
  1407. NodeMixin.get(self),
  1408. type=NodeMixin.get_wrapped_type(wrapped),
  1409. attr_name=name,
  1410. name="",
  1411. ),
  1412. )
  1413. return wrapped
  1414. class _expr_iter:
  1415. def __init__(self, graph: InternalGraph, recursive: bool = True):
  1416. self.graph = graph
  1417. self.recursive = recursive
  1418. self._visited_graph = set()
  1419. def __iter__(self):
  1420. yield from self._gen_expr(self.graph)
  1421. def _gen_expr(self, graph: InternalGraph):
  1422. visit_inp = set()
  1423. for inp_node in graph.inputs:
  1424. if inp_node not in visit_inp:
  1425. yield inp_node.expr
  1426. visit_inp.add(inp_node)
  1427. for expr in graph._exprs:
  1428. yield expr
  1429. if (
  1430. self.recursive
  1431. and hasattr(expr, "graph")
  1432. and expr.graph is not None
  1433. and id(expr.graph) not in self._visited_graph
  1434. ):
  1435. self._visited_graph.add(id(expr.graph))
  1436. yield from self._gen_expr(expr.graph)
  1437. class _node_iter:
  1438. def __init__(self, graph: InternalGraph, recursive: bool = True) -> None:
  1439. nodes = []
  1440. node_ids = set()
  1441. for expr in graph.exprs(recursive):
  1442. for n in expr.outputs:
  1443. assert id(n) not in node_ids
  1444. nodes.append(n)
  1445. node_ids.add(id(n))
  1446. self.nodes = nodes
  1447. def __iter__(self):
  1448. for node in self.nodes:
  1449. yield node
  1450. class BaseFilter:
  1451. r"""``BaseFilter`` exposes some methods for converting ``_node_iter/_expr_iter`` to ``list``, ``dict``, etc."""
  1452. def __init__(self, iter: Iterable):
  1453. self._iter = iter
  1454. def __iter__(self):
  1455. return iter(self._iter)
  1456. def as_list(self):
  1457. r"""Consume this iterator and return its content as a list.
  1458. Returns:
  1459. A list of ``Node`` or ``Expr``.
  1460. """
  1461. return list(self)
  1462. def as_dict(self):
  1463. r"""Construct an ordered dict to map from ``id`` to objects in this iterator.
  1464. Returns:
  1465. An :class:`OrderedDict`.
  1466. """
  1467. return collections.OrderedDict((i._id, i) for i in self)
  1468. def as_unique(self):
  1469. """Assert that this iterator yields only one ``Node`` or ``Expr`` and return it.
  1470. Rerurns:
  1471. A ``Node`` or ``Expr``.
  1472. """
  1473. rst = self.as_list()
  1474. assert len(rst) == 1, "{} elements found".format(len(rst))
  1475. (elem,) = self
  1476. return elem
  1477. def as_count(self):
  1478. r"""Consume this iterator and get the number of elements."""
  1479. return sum(1 for _ in self)
  1480. class ExprFilter(BaseFilter):
  1481. """Filter on Expr iterator.
  1482. This class is an iterator of :class:`.Expr` objects and multiple
  1483. filtering conditions and mappers can be chained.
  1484. """
  1485. def call_function(self, func):
  1486. r"""Filter by specific ``CallFunction.func``.
  1487. See :meth:`~.InternalGraph.get_function_by_type` for details.
  1488. """
  1489. return ExprFilterCallFunction(self, func)
  1490. def call_method(self, method):
  1491. r"""Filter by specific ``CallMethod.method``.
  1492. See :meth:`~.InternalGraph.get_function_by_type` for details.
  1493. """
  1494. return ExprFilterCallMethod(self, method)
  1495. def expr_id(self, expr_id: List[int]):
  1496. r"""Filter Exprs by their ``id``.
  1497. See :meth:`~.InternalGraph.get_function_by_type` for details.
  1498. """
  1499. return ExprFilterExprId(self, expr_id)
  1500. class NodeFilter(BaseFilter):
  1501. """Filter on Node iterator.
  1502. This class is an iterator of :class:`.Node` objects and multiple
  1503. filtering conditions and mappers can be chained.
  1504. """
  1505. def type(self, owner_type):
  1506. r"""Filter by specific Module type.
  1507. See :meth:`~.InternalGraph.get_module_by_type` for details.
  1508. """
  1509. return NodeFilterType(self, owner_type)
  1510. def node_id(self, node_id: List[int]):
  1511. r"""Filter Nodes by their ``id``.
  1512. See :meth:`~.InternalGraph.get_node_by_id` for details.
  1513. """
  1514. return NodeFilterNodeId(self, node_id)
  1515. def name(self, name: str, ignorecase: bool = True):
  1516. r"""Filter Nodes by their full name.
  1517. See :meth:`~.InternalGraph.get_node_by_name` for details.
  1518. """
  1519. return NodeFilterName(self, name, ignorecase)
  1520. class NodeFilterType(NodeFilter):
  1521. """See :meth:`~.InternalGraph.get_module_by_type`"""
  1522. def __init__(self, expr_iter, owner_type):
  1523. super().__init__(expr_iter)
  1524. self.owner_type = owner_type
  1525. def __iter__(self):
  1526. for node in self._iter:
  1527. if not isinstance(node, ModuleNode):
  1528. continue
  1529. if not hasattr(node, "owner"):
  1530. continue
  1531. if isinstance(node.owner, self.owner_type):
  1532. yield node
  1533. class NodeFilterNodeId(NodeFilter):
  1534. """See :meth:`~.InternalGraph.get_node_by_id`"""
  1535. def __init__(self, expr_iter, node_id: List[int]):
  1536. super().__init__(expr_iter)
  1537. if not isinstance(node_id, Sequence):
  1538. node_id = [node_id]
  1539. self.node_id = node_id
  1540. def __iter__(self):
  1541. for node in self._iter:
  1542. if node._id in self.node_id:
  1543. yield node
  1544. class NodeFilterName(NodeFilter):
  1545. """See :meth:`~.InternalGraph.get_node_by_name`"""
  1546. _re = None
  1547. def __init__(self, node_iter, pattern, ignorecase):
  1548. super().__init__(node_iter)
  1549. self.pattern = pattern
  1550. self._re = self.make_re(pattern, ignorecase)
  1551. @classmethod
  1552. def make_re(cls, pattern, ignorecase=True):
  1553. assert isinstance(pattern, str), "bad pattern: {!r}".format(pattern)
  1554. assert isinstance(ignorecase, bool)
  1555. flags = 0
  1556. if ignorecase:
  1557. flags |= re.IGNORECASE
  1558. return re.compile(fnmatch.translate(pattern), flags=flags)
  1559. def __iter__(self):
  1560. for i in self._iter:
  1561. graph = i.top_graph
  1562. name = "{}_{}".format(graph._name, i._name)
  1563. if self.pattern == name or self._re.match(name):
  1564. yield i
  1565. class ExprFilterCallFunction(ExprFilter):
  1566. """See :meth:`~.InternalGraph.get_function_by_type`"""
  1567. def __init__(self, expr_iter, func: Callable = None):
  1568. super().__init__(expr_iter)
  1569. self.func = func
  1570. def __iter__(self):
  1571. for expr in self._iter:
  1572. if not isinstance(expr, CallFunction):
  1573. continue
  1574. if self.func is None or expr.func == self.func:
  1575. yield expr
  1576. class ExprFilterCallMethod(ExprFilter):
  1577. """See :meth:`~.InternalGraph.get_method_by_type`"""
  1578. def __init__(self, expr_iter, method: str = None):
  1579. super().__init__(expr_iter)
  1580. self.method = method
  1581. def __iter__(self):
  1582. for expr in self._iter:
  1583. if not isinstance(expr, CallMethod):
  1584. continue
  1585. if self.method is None or expr.method == self.method:
  1586. yield expr
  1587. class ExprFilterExprId(ExprFilter):
  1588. """See :meth:`~.InternalGraph.get_expr_by_id`"""
  1589. def __init__(self, expr_iter, expr_id: List[int]):
  1590. super().__init__(expr_iter)
  1591. if not isinstance(expr_id, Sequence):
  1592. expr_id = [expr_id]
  1593. self.expr_id = expr_id
  1594. def __iter__(self):
  1595. for expr in self._iter:
  1596. if expr._id in self.expr_id:
  1597. yield expr
  1598. class TracedModule(Module):
  1599. r"""``TracedModule`` is the Module created by tracing normal module.
  1600. It owns an argdef to graph(InternalGraph) map. The forward method of ``TracedModule``
  1601. will get a graph from ``argdef_graph_map`` according to the argdef of input ``args/kwargs``
  1602. and interpret it.
  1603. .. note::
  1604. ``TracedModule`` can only be created by :func:`~.trace_module`. See :func:`~.trace_module`
  1605. for more details.
  1606. """
  1607. # m_node = None # type: ModuleNode
  1608. argdef_graph_map = None
  1609. argdef_outdef_map = None
  1610. def __init__(self, is_top, argdef_graph_map, argdef_outdef_map, is_qat=False):
  1611. super(TracedModule, self).__init__()
  1612. self.argdef_graph_map = argdef_graph_map
  1613. self.argdef_outdef_map = argdef_outdef_map
  1614. self._is_top = is_top
  1615. self.watch_points = []
  1616. self.watch_node_value = {}
  1617. self.end_points = []
  1618. self.is_qat = is_qat
  1619. def forward(self, *args, **kwargs):
  1620. inputs, treedef = tree_flatten(((self, *args), kwargs))
  1621. assert treedef in self.argdef_graph_map
  1622. inputs = filter(
  1623. lambda i: isinstance(i, (Module, TracedModuleBuilder, RawTensor)), inputs
  1624. ) # allow TracedModuleBuilder for retrace.
  1625. outputs = self.argdef_graph_map[treedef].interpret(*inputs)
  1626. if self.watch_points:
  1627. self.watch_node_value = {}
  1628. for n in self.watch_points:
  1629. self.watch_node_value[n] = n.top_graph._rst.pop(n)
  1630. if self.end_points:
  1631. return outputs
  1632. out_def = self.argdef_outdef_map[treedef]
  1633. outputs = out_def.unflatten(outputs)
  1634. return outputs
  1635. def set_watch_points(self, nodes):
  1636. r"""Initialize the :attr:`~.TracedModule.watch_points`.
  1637. You can call this function to get the ``Tensor/Module`` corresponding to a ``Node`` at runtime.
  1638. Args:
  1639. nodes: a list of ``Node``.
  1640. For example, the following code
  1641. .. code-block::
  1642. import megengine.module as M
  1643. import megengine as mge
  1644. import megengine.traced_module as tm
  1645. class MyModule(M.Module):
  1646. def forward(self, x):
  1647. x = x + 1 + 2
  1648. return x
  1649. net = MyModule()
  1650. inp = mge.Tensor([0])
  1651. traced_module = tm.trace_module(net, inp)
  1652. add_1_node = traced_module.graph.get_node_by_id(2).as_unique()
  1653. traced_module.set_watch_points(add_1_node)
  1654. out = traced_module(inp)
  1655. Will get the following ``watch_node_value``::
  1656. print(traced_module.watch_node_value)
  1657. .. code-block:: text
  1658. {add_out: Tensor([1.], device=xpux:0)}
  1659. """
  1660. if not isinstance(nodes, Sequence):
  1661. nodes = [nodes]
  1662. self.watch_points = nodes
  1663. if nodes:
  1664. nodes[0].top_graph._watch_point = []
  1665. for n in nodes:
  1666. n.top_graph._watch_point.append(n)
  1667. def clear_watch_points(self):
  1668. r"""Clear the :attr:`~.TracedModule.watch_points` and :attr:`~.TracedModule.watch_node_value`.
  1669. """
  1670. for n in self.watch_points:
  1671. n.top_graph._watch_point = []
  1672. self.watch_points = []
  1673. self.watch_node_value = {}
  1674. def set_end_points(self, nodes: Sequence[Node]):
  1675. r"""Initialize the :attr:`~.TracedModule.end_points`.
  1676. When all the ``nodes`` are generated, the Module will stop execution and return directly.
  1677. Args:
  1678. nodes: a list of ``Node``.
  1679. For example, the following code
  1680. .. code-block::
  1681. import megengine.module as M
  1682. import megengine as mge
  1683. import megengine.traced_module as tm
  1684. class MyModule(M.Module):
  1685. def forward(self, x):
  1686. x = x + 1 + 2
  1687. return x
  1688. net = MyModule()
  1689. inp = mge.Tensor([0])
  1690. traced_module = tm.trace_module(net, inp)
  1691. add_1_node = traced_module.graph.get_node_by_id(2).as_unique()
  1692. traced_module.set_end_points(add_1_node)
  1693. out = traced_module(inp)
  1694. Will get the following ``out``::
  1695. print(out)
  1696. .. code-block:: text
  1697. [Tensor([1.], device=xpux:0)]
  1698. """
  1699. if not isinstance(nodes, Sequence):
  1700. nodes = [nodes]
  1701. self.end_points = nodes
  1702. graphs = list(self.argdef_graph_map.values())
  1703. for n in nodes:
  1704. assert n.top_graph in graphs
  1705. n.top_graph._end_point.append(n)
  1706. def clear_end_points(self):
  1707. r"""Clear the :attr:`~.TracedModule.end_points`.
  1708. """
  1709. for n in self.end_points:
  1710. n.top_graph._end_point = []
  1711. self.end_points = []
  1712. @property
  1713. def graph(self) -> InternalGraph:
  1714. """Return the ``InternalGraph`` of this ``TracedModule``.
  1715. """
  1716. assert len(self.argdef_graph_map) == 1
  1717. return list(self.argdef_graph_map.values())[0]
  1718. def _update_ref(self, actual_node_map: Union[Dict] = None, top_graph=None):
  1719. for inp_def, graph in self.argdef_graph_map.items():
  1720. if top_graph is not None:
  1721. graph._top_graph = weakref.ref(top_graph)
  1722. for n in graph._inputs + graph.outputs:
  1723. n._top_graph = weakref.ref(graph)
  1724. graph._inputs[0]._owner = weakref.ref(self)
  1725. for i, n in enumerate(graph._inputs):
  1726. n.actual_node = []
  1727. if actual_node_map is not None and inp_def in actual_node_map.keys():
  1728. n.actual_node = list(list(zip(*(actual_node_map[inp_def])))[i])
  1729. node2obj = {}
  1730. next_actual_node_map = collections.defaultdict(
  1731. lambda: collections.defaultdict(list)
  1732. )
  1733. node2obj[graph._inputs[0]] = self
  1734. for expr in graph._exprs:
  1735. for n in expr.inputs + expr.outputs:
  1736. n._top_graph = weakref.ref(graph)
  1737. expr._top_graph = weakref.ref(graph)
  1738. if isinstance(expr, GetAttr) and isinstance(
  1739. expr.outputs[0], ModuleNode
  1740. ):
  1741. obj = expr.interpret(node2obj[expr.inputs[0]])[0]
  1742. expr.outputs[0]._owner = weakref.ref(obj)
  1743. node2obj[expr.outputs[0]] = obj
  1744. if isinstance(expr, Constant) and isinstance(
  1745. expr.outputs[0], ModuleNode
  1746. ):
  1747. obj = expr.value
  1748. expr.outputs[0]._owner = weakref.ref(obj)
  1749. node2obj[expr.outputs[0]] = obj
  1750. if (
  1751. isinstance(expr, CallMethod)
  1752. and expr.method == "__call__"
  1753. and isinstance(expr.inputs[0], ModuleNode)
  1754. ):
  1755. obj = node2obj[expr.inputs[0]]
  1756. if expr.arg_def is not None:
  1757. next_actual_node_map[obj][expr.arg_def].append(expr.inputs)
  1758. for obj in node2obj.values():
  1759. if obj is self:
  1760. continue
  1761. mnode_map = None
  1762. if obj in next_actual_node_map.keys():
  1763. mnode_map = next_actual_node_map[obj]
  1764. if isinstance(obj, TracedModule):
  1765. obj._update_ref(mnode_map, graph)
  1766. def flatten(self):
  1767. r"""Get a new TracedModule, which eliminates ``GetAttr`` and has no hierarchy.
  1768. Retruns:
  1769. A new :class:`TracedModule`.
  1770. """
  1771. new_module = copy.deepcopy(self)
  1772. def _replace_inputs_and_outputs(expr: Expr, repl_dict: Dict[Node, Node]):
  1773. inputs, outputs = expr.inputs, expr.outputs
  1774. for i, node in enumerate(inputs):
  1775. if node in repl_dict:
  1776. inputs[i] = repl_dict[node]
  1777. for i, node in enumerate(outputs):
  1778. if node in repl_dict:
  1779. outputs[i] = repl_dict[node]
  1780. outputs[i].expr = expr
  1781. def _flatten_subgraph(
  1782. parent_graph: InternalGraph,
  1783. graph: InternalGraph,
  1784. call: CallMethod,
  1785. module: Module,
  1786. ):
  1787. repl_dict, node2obj, rename_blacklist = {}, {}, []
  1788. if call is not None:
  1789. graph = copy.deepcopy(graph)
  1790. node2obj[call.inputs[0]] = module
  1791. repl_dict = dict(zip(graph._inputs, call.inputs))
  1792. for ind, out in enumerate(graph.outputs):
  1793. if isinstance(out.expr, Input):
  1794. assert out in repl_dict
  1795. call_out = call.outputs[ind]
  1796. for expr in call.outputs[ind].users:
  1797. for index, inp in enumerate(expr.inputs):
  1798. if inp is call_out:
  1799. expr.inputs[index] = repl_dict[out]
  1800. repl_dict[out].users.append(expr)
  1801. if parent_graph is not None:
  1802. for index, parent_out in enumerate(parent_graph._outputs):
  1803. if parent_out is call_out:
  1804. parent_graph._outputs[index] = repl_dict[out]
  1805. continue
  1806. repl_dict[out] = call.outputs[ind]
  1807. if isinstance(out, TensorNode):
  1808. call.outputs[ind]._qualname = out._qualname
  1809. for node, repl_node in repl_dict.items():
  1810. assert node in graph._inputs or node in graph._outputs
  1811. repl_node.users.extend(node.users)
  1812. rename_blacklist = list(chain(call.inputs, call.outputs))
  1813. node2obj[graph._inputs[0]] = module
  1814. prefix_name = call.inputs[0]._name if call else ""
  1815. flattened_exprs = []
  1816. for expr in graph._exprs:
  1817. exprs = [expr]
  1818. if call is not None:
  1819. _replace_inputs_and_outputs(expr, repl_dict)
  1820. if isinstance(expr, GetAttr):
  1821. mnode = expr.inputs[0]
  1822. node2obj[expr.outputs[0]] = expr.interpret(node2obj[mnode])[0]
  1823. if isinstance(expr, CallMethod):
  1824. obj_node = expr.inputs[0]
  1825. if isinstance(obj_node, ModuleNode) and isinstance(
  1826. obj_node.expr, GetAttr
  1827. ):
  1828. obj = node2obj[obj_node]
  1829. expr_graph = (
  1830. obj.argdef_graph_map[expr.arg_def]
  1831. if hasattr(obj, "argdef_graph_map")
  1832. else None
  1833. )
  1834. if expr_graph is not None and not obj.is_qat:
  1835. exprs = _flatten_subgraph(graph, expr_graph, expr, obj)
  1836. if parent_graph is not None:
  1837. for node in expr.outputs:
  1838. name = node._name
  1839. if node not in rename_blacklist:
  1840. name = "{}_{}".format(prefix_name, name)
  1841. node._name = parent_graph._namespace.create_unique_name(
  1842. name, node
  1843. )
  1844. flattened_exprs.extend(exprs)
  1845. if call is not None:
  1846. for i in call.inputs:
  1847. i.users.remove(call)
  1848. return flattened_exprs
  1849. new_module.graph._exprs = _flatten_subgraph(
  1850. None, new_module.graph, None, new_module
  1851. )
  1852. new_module.graph._re_associate_name()
  1853. new_module.graph.compile()
  1854. new_module._update_ref()
  1855. new_module.graph._reset_ids()
  1856. return new_module
  1857. def __getstate__(self):
  1858. d = self.__dict__.copy()
  1859. for k in Module.__dict__:
  1860. d.pop(k, None)
  1861. _check_obj_attr(d)
  1862. for k in d:
  1863. if module_tracer.is_builtin(d[k]):
  1864. assert _check_builtin_module_attr(
  1865. d[k]
  1866. ), "Module {} can not be serialized. ".format(type(d[k]))
  1867. d[k] = _ModuleState.get_module_state(d[k])
  1868. dump_info = {
  1869. "version": __version__,
  1870. "register_type": USER_REGISTERED_LEAF_TYPE,
  1871. "register_container_type": USER_REGISTERED_CONTAINER_TYPE,
  1872. "register_mdule": USER_REGISTERED_MODULE,
  1873. "register_function": USER_REGISTERED_FUNCTION,
  1874. }
  1875. d["dump_info"] = dump_info
  1876. return d
  1877. def __setstate__(self, state):
  1878. for k, v in state.items():
  1879. if isinstance(v, _ModuleState):
  1880. state[k] = v.to_module()
  1881. self.__dict__.update(state)
  1882. self._update_ref()
  1883. for _, graph in self.argdef_graph_map.items():
  1884. for expr in graph._exprs:
  1885. if isinstance(expr, CallFunction):
  1886. load_functional(expr)
  1887. if isinstance(expr, CallMethod):
  1888. if expr.method == "__call__":
  1889. load_call_module_expr(expr)
  1890. else:
  1891. load_call_tensor_method_expr(expr)
  1892. if isinstance(expr, Apply):
  1893. load_apply_expr(expr)
  1894. for _, graph in self.argdef_graph_map.items():
  1895. ind = 0
  1896. while ind < len(graph._exprs):
  1897. cur_expr = graph._exprs[ind]
  1898. has_new_expr = False
  1899. for i in cur_expr.inputs:
  1900. if i.expr not in graph._exprs and not isinstance(i.expr, Input):
  1901. graph._exprs.insert(ind, i.expr)
  1902. has_new_expr = True
  1903. if not has_new_expr:
  1904. ind += 1
  1905. for expr in graph._exprs:
  1906. for i in expr.inputs:
  1907. if expr.inputs.count(i) != i.users.count(expr):
  1908. add_or_del_count = expr.inputs.count(i) - i.users.count(expr)
  1909. if add_or_del_count > 0:
  1910. i.users.extend([expr] * add_or_del_count)
  1911. else:
  1912. [i.users.remove(expr) for i in range(-add_or_del_count)]
  1913. for o in expr.outputs:
  1914. if o.expr is not expr:
  1915. assert o not in o.expr.outputs
  1916. o.expr = expr
  1917. for node in graph.nodes(False):
  1918. # remove users of node which doesn't use node as input
  1919. node.users = [e for e in node.users if node in e.inputs]
  1920. for expr in graph._exprs:
  1921. graph._namespace.auto_naming_for_outputs(expr)
  1922. self._update_ref()
  1923. for _, graph in self.argdef_graph_map.items():
  1924. graph._reset_ids()
  1925. def __copy__(self):
  1926. cls = self.__class__
  1927. result = cls.__new__(cls)
  1928. result.__dict__.update(self.__dict__)
  1929. return result
  1930. def __deepcopy__(self, memo):
  1931. cls = self.__class__
  1932. result = cls.__new__(cls)
  1933. state = {}
  1934. memo[id(self)] = result
  1935. for k, v in self.__dict__.items():
  1936. if not isinstance(v, weakref.ReferenceType):
  1937. state[k] = copy.deepcopy(v, memo)
  1938. result.__dict__.update(state)
  1939. result._update_ref()
  1940. return result
  1941. def cpp_apply_module_trace(opdef, *args):
  1942. return Apply.apply_module_trace_hook(opdef, *args)
  1943. USER_REGISTERED_MODULE = []
  1944. USER_REGISTERED_FUNCTION = []
  1945. def register_as_builtin(mod_cls: Type[Module]) -> None:
  1946. r"""Registers class ``mod_cls`` (subclass of :class:`~.Module`) as builtin module.
  1947. Args:
  1948. mod_cls: the module class which will be treated as builtin module in tracing.
  1949. """
  1950. USER_REGISTERED_MODULE.append((mod_cls.__module__, mod_cls.__qualname__))
  1951. module_tracer.register_as_builtin(mod_cls)
  1952. def wrap(func: Callable):
  1953. r"""Call this function to register ``func`` as a builtin function.
  1954. This function can be called at module-level scope to register ``func`` as a builtin function.
  1955. A builtin function will be converted to a :class:`CallFunction` Expr in tracing::
  1956. def my_func(x, y):
  1957. return x + y
  1958. import megengine.traced_module as tm
  1959. tm.wrap(my_func)
  1960. This function can also equivalently be used as a decorator::
  1961. @tm.wrap
  1962. def my_func(x, y):
  1963. return x + y
  1964. Args:
  1965. func: the function of the global function to insert into the graph when it's called.
  1966. """
  1967. USER_REGISTERED_FUNCTION.append((func.__module__, func.__qualname__))
  1968. assert callable(func), "func must be a callable"
  1969. assert hasattr(func, "__code__")
  1970. fn_name = func.__code__.co_name
  1971. currentframe = inspect.currentframe()
  1972. assert currentframe is not None
  1973. f = currentframe.f_back
  1974. assert f is not None
  1975. assert (
  1976. f.f_code.co_name == "<module>"
  1977. ), "wrap must be called at the top level of a module"
  1978. Patcher._builtin_functions.append((f.f_globals, fn_name))
  1979. return func
  1980. def _register_all_builtin_module():
  1981. for sub_mod in [M, M.qat, M.quantized]:
  1982. for m in getmembers(sub_mod):
  1983. if (
  1984. isclass(m[1])
  1985. and issubclass(m[1], M.Module)
  1986. and m[1] is not M.Sequential
  1987. ):
  1988. module_tracer.register_as_builtin(m[1])
  1989. module_tracer.register_as_builtin(Observer)
  1990. module_tracer.register_as_builtin(MinMaxObserver)
  1991. module_tracer.register_as_builtin(SyncMinMaxObserver)
  1992. module_tracer.register_as_builtin(ExponentialMovingAverageObserver)
  1993. module_tracer.register_as_builtin(SyncExponentialMovingAverageObserver)
  1994. module_tracer.register_as_builtin(HistogramObserver)
  1995. module_tracer.register_as_builtin(PassiveObserver)
  1996. module_tracer.register_as_builtin(LSQ)
  1997. module_tracer.register_as_builtin(TQT)
  1998. module_tracer.register_as_builtin(FakeQuantize)
  1999. module_tracer.register_as_builtin(TM_FakeQuant)
  2000. def trace_module(
  2001. mod: Module, *args: Tuple[Any], **kwargs: Dict[str, Any]
  2002. ) -> TracedModule:
  2003. r"""Traces module ``mod`` and returns corresponding :class:`TracedModule`.
  2004. Args:
  2005. mod: the module will be converted to :class:`TracedModule`.
  2006. args: the positional arguments passed to forward method of ``mod``.
  2007. kwargs: the keyword arguments passed to forward method of ``mod``.
  2008. """
  2009. assert active_module_tracer() is None
  2010. assert isinstance(mod, Module)
  2011. try:
  2012. net_name = mod._name if mod._name else mod.__class__.__name__
  2013. use_sym_shape = set_symbolic_shape(True)
  2014. set_module_tracing()
  2015. set_active_module_tracer(module_tracer(_wrapped_function))
  2016. for cls in [Expr, Node]:
  2017. cls._set_next_id(0)
  2018. with active_module_tracer().patcher:
  2019. global_scope = InternalGraph(name="top", qualname=net_name)
  2020. active_module_tracer().push_scope(global_scope)
  2021. builder = TracedModuleBuilder(mod, True)
  2022. NodeMixin.wrap_safe(
  2023. builder, Input.make(name="top", type=ModuleNode, qualname=net_name)
  2024. )
  2025. args, kwargs = _convert_kwargs_to_args(mod.forward, args, kwargs, True)
  2026. inputs, _ = tree_flatten((args, kwargs))
  2027. for _, i in enumerate(inputs):
  2028. # assert isinstance(i, Tensor), "not support "
  2029. if isinstance(i, RawTensor):
  2030. NodeMixin.wrap_safe(
  2031. i,
  2032. Input.make(
  2033. name="arg_{}".format(_),
  2034. type=NodeMixin.get_wrapped_type(i),
  2035. qualname="{}.[{}]".format(net_name, "arg_{}".format(_)),
  2036. ),
  2037. )
  2038. builder(*args, **kwargs)
  2039. active_module_tracer().pop_scope()
  2040. traced_mod = builder.build()
  2041. traced_mod.graph._reset_ids()
  2042. return traced_mod
  2043. finally:
  2044. set_symbolic_shape(use_sym_shape)
  2045. set_active_module_tracer(None)
  2046. unset_module_tracing()

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台