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

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

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