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. active_module_tracer().patcher.__exit__(ty, va, tr)
  251. _set_convert_node_flag(False)
  252. while self._tensor_method_patch:
  253. pf = self._tensor_method_patch.pop()
  254. pf.set_func(pf.origin_fn)
  255. module = self.graph.inputs[0].owner
  256. for k, v in module.__dict__.items():
  257. if isinstance(v, TracedModuleBuilder):
  258. v = v.build()
  259. setattr(module, k, v)
  260. set_symbolic_shape(self.use_sym_shape)
  261. set_active_module_tracer(None)
  262. unset_module_tracing()
  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. return self.nodes(recursive).type(module_cls)
  541. def get_node_by_id(self, node_id: List[int] = None, recursive=True):
  542. r"""Filter Nodes by their ``id``.
  543. The ``id`` of the ``Node`` can be obtained by the following code
  544. .. code-block::
  545. # node : Node
  546. print("{:i}".format(node))
  547. print(node.__format__("i"))
  548. # graph : InternalGraph
  549. print("{:i}".format(graph))
  550. print(graph.__format__("i"))
  551. Args:
  552. node_id: a list of :class:`int`.
  553. recursive: whether to get the Nodes in the subgraph.
  554. Default: True
  555. Returns:
  556. A :class:`~.TracedModule.NodeFilterNodeId`.
  557. """
  558. return self.nodes(recursive).node_id(node_id)
  559. def get_node_by_name(
  560. self, name: str = None, ignorecase: bool = True, recursive=True
  561. ):
  562. r"""Filter Nodes by their full name.
  563. The full name of the ``Node`` can be obtained by the following code
  564. .. code-block::
  565. # node : Node
  566. print("{:p}".format(node))
  567. print(node.__format__("p"))
  568. # graph : InternalGraph
  569. print("{:p}".format(graph))
  570. print(graph.__format__("p"))
  571. Args:
  572. name: a string in glob syntax that can contain ``?`` and
  573. ``*`` to match a single or arbitrary characters.
  574. ignorecase: whether to ignroe case.
  575. Default: True
  576. recursive: whether to get the Nodes in the subgraph.
  577. Default: True
  578. Returns:
  579. A :class:`~.TracedModule.NodeFilterName`.
  580. """
  581. return self.nodes(recursive).name(name, ignorecase)
  582. def _add_input(self, i):
  583. self._inputs.append(i)
  584. def _add_output(self, o):
  585. self._outputs.append(o)
  586. def get_dep_exprs(self, nodes: Sequence[Node]) -> List[Expr]:
  587. r"""Get the dependent Exprs of the ``nodes``.
  588. Args:
  589. nodes: a list of :class:`Node`.
  590. Returns:
  591. A list of dependent :class:`Expr`.
  592. """
  593. if not isinstance(nodes, Sequence):
  594. nodes = (nodes,)
  595. ret = list()
  596. queue = list(nodes)
  597. visited_queue = list()
  598. while queue:
  599. node = queue.pop()
  600. visited_queue.append(node)
  601. expr = node.expr
  602. if expr not in ret:
  603. ret.append(expr)
  604. for i in expr.inputs:
  605. if i not in queue and i not in visited_queue:
  606. queue.append(i)
  607. return ret
  608. def reset_inputs(self, *args, **kwargs):
  609. forma_mnode = self.inputs[0]
  610. moudle = forma_mnode.owner
  611. assert moudle._is_top, "reset_inputs only supports top graph"
  612. inputs, tree_def = tree_flatten(((moudle, *args), kwargs))
  613. def create_node(val: Tensor):
  614. name = self._namespace.create_unique_name("args")
  615. node = Input(
  616. type=TensorNode, name=name, qualname="%s.[%s]" % (self._qualname, name)
  617. ).outputs[0]
  618. self._namespace.associate_name_with_obj(node.name, node)
  619. node.shape = val.shape
  620. node.dtype = val.dtype
  621. return node
  622. formal_node_inputs = [
  623. forma_mnode,
  624. ]
  625. org_argdef = list(moudle.argdef_graph_map.keys())[0]
  626. for v in inputs[1:]:
  627. assert isinstance(v, RawTensor)
  628. formal_node_inputs.append(create_node(v))
  629. self._inputs[:] = formal_node_inputs
  630. moudle.argdef_graph_map[tree_def] = moudle.argdef_graph_map.pop(org_argdef)
  631. moudle.argdef_outdef_map[tree_def] = moudle.argdef_outdef_map.pop(org_argdef)
  632. return formal_node_inputs[1:]
  633. def add_input_node(
  634. self, shape: Tuple[int], dtype: str = "float32", name: str = "args"
  635. ):
  636. r"""Add an input node to the graph.
  637. The new Node will be the last of the positional arguments.
  638. Args:
  639. shape: the shape of the new input Node.
  640. dtype: the dtype of the new input Node.
  641. Default: float32
  642. name: the name of the new input Node. When the name is used in the graph,
  643. a suffix will be added to it.
  644. """
  645. forma_mnode = self.inputs[0]
  646. moudle = forma_mnode.owner
  647. assert moudle._is_top, "add_input_node only supports top graph"
  648. def create_node(name=None):
  649. name = self._namespace.create_unique_name(name)
  650. node = Input(
  651. type=TensorNode, name=name, qualname="%s.[%s]" % (self._qualname, name)
  652. ).outputs[0]
  653. self._namespace.associate_name_with_obj(node.name, node)
  654. node.shape = shape
  655. node.dtype = dtype
  656. return node
  657. org_argdef = list(moudle.argdef_graph_map.keys())[0]
  658. args, kwargs = org_argdef.unflatten(self._inputs)
  659. formal_inp_node = create_node(name)
  660. inputs, tree_def = tree_flatten(
  661. ((*args, formal_inp_node), kwargs),
  662. is_const_leaf=lambda x: not isinstance(x, (TensorNode, ModuleNode)),
  663. )
  664. self._inputs[:] = inputs[:]
  665. moudle.argdef_graph_map[tree_def] = moudle.argdef_graph_map.pop(org_argdef)
  666. moudle.argdef_outdef_map[tree_def] = moudle.argdef_outdef_map.pop(org_argdef)
  667. return formal_inp_node
  668. def reset_outputs(self, outputs):
  669. r"""Reset the output Nodes of the graph.
  670. .. note::
  671. This method only supports resetting the output of graphs
  672. that do not have a parent graph.
  673. Args:
  674. outputs: an object which inner element is Node. Support tuple, list
  675. dict, etc.
  676. For example, the following code
  677. .. code-block::
  678. import megengine.functional as F
  679. import megengine.module as M
  680. import megengine.traced_module as tm
  681. class MyModule(M.Module):
  682. def forward(self, x):
  683. x = x + 1
  684. return x
  685. net = MyModule()
  686. inp = F.zeros(shape = (1, ))
  687. traced_module = tm.trace_module(net, inp)
  688. graph = traced_module.graph
  689. inp_node = graph.inputs[1]
  690. out_node = graph.outputs[0]
  691. graph.reset_outputs((out_node, {"input": inp_node}))
  692. out = traced_module(inp)
  693. Will produce the following ``InternalGraph`` and ``out``::
  694. print(graph)
  695. print(out)
  696. .. code-block:: text
  697. MyModule.Graph (self, x) {
  698. %2: add_out = x.__add__(1, )
  699. return add_out, x
  700. }
  701. (Tensor([1.], device=xpux:0), {'input': Tensor([0.], device=xpux:0)})
  702. """
  703. outputs, out_def = tree_flatten(
  704. outputs, is_leaf=lambda x: isinstance(x, TensorNode),
  705. )
  706. forma_mnode = self.inputs[0]
  707. moudle = forma_mnode.owner
  708. assert moudle._is_top, "reset_outputs only supports top graph"
  709. tree_def = list(moudle.argdef_graph_map.keys())[0]
  710. self._outputs[:] = outputs
  711. moudle.argdef_outdef_map[tree_def] = out_def
  712. def add_output_node(self, node: TensorNode):
  713. r"""Add an output node to the Graph.
  714. The Graph output will become a ``tuple`` after calling ``add_output_node``.
  715. The first element of the ``tuple`` is the original output, and the second
  716. is the ``node``.
  717. For example, the following code
  718. .. code-block::
  719. import megengine.functional as F
  720. import megengine.module as M
  721. import megengine.traced_module as tm
  722. class MyModule(M.Module):
  723. def forward(self, x):
  724. x = x + 1
  725. return x
  726. net = MyModule()
  727. inp = F.zeros(shape = (1, ))
  728. traced_module = tm.trace_module(net, inp)
  729. graph = traced_module.graph
  730. inp_node = graph.inputs[1]
  731. out_node = graph.outputs[0]
  732. graph.add_output_node(inp_node)
  733. graph.add_output_node(out_node)
  734. out = traced_module(inp)
  735. Will produce the following ``InternalGraph`` and ``out``::
  736. print(graph)
  737. print(out)
  738. .. code-block:: text
  739. MyModule.Graph (self, x) {
  740. %2: add_out = x.__add__(1, )
  741. return add_out, x, add_out
  742. }
  743. ((Tensor([1.], device=xpux:0), Tensor([0.], device=xpux:0)), Tensor([1.], device=xpux:0))
  744. """
  745. forma_mnode = self.inputs[0]
  746. moudle = forma_mnode.owner
  747. assert moudle._is_top, "add_output_node only supports top graph"
  748. tree_def = list(moudle.argdef_graph_map.keys())[0]
  749. org_out_def = moudle.argdef_outdef_map[tree_def]
  750. org_outs = org_out_def.unflatten(self._outputs)
  751. outputs, out_def = tree_flatten(
  752. (org_outs, node), is_leaf=lambda x: isinstance(x, TensorNode),
  753. )
  754. self._outputs[:] = outputs
  755. moudle.argdef_outdef_map[tree_def] = out_def
  756. def insert_exprs(self, expr: Optional[Expr] = None):
  757. r"""Initialize the trace mode and insertion position.
  758. When used within a 'with' statement, this will temporary set the trace mode and
  759. then restore normal mode when the with statement exits::
  760. with graph.insert_exprs(e): # set the trace mode
  761. ... # trace function or module
  762. ... # inert exprs into graph and resotre normal mode
  763. Args:
  764. expr: the ``expr`` after which to insert. If None, the insertion position will be
  765. automatically set based on the input node.
  766. Returns:
  767. A resource manager that will initialize trace mode on ``__enter__`` and
  768. restore normal mode on ``__exit__``.
  769. """
  770. if expr is not None:
  771. assert expr.top_graph == self, "Expr to insert after is not in graph."
  772. return _InsertExprs(self, expr)
  773. def replace_node(self, repl_dict: Dict[Node, Node]):
  774. r"""Replace the Nodes in the graph.
  775. Args:
  776. repl_dict: the map {old_Node: new_Node} that specifies how to replace the Nodes.
  777. """
  778. while repl_dict:
  779. node, repl_node = repl_dict.popitem()
  780. assert type(node) == type(
  781. repl_node
  782. ), "The type of {}({}) and {}({}) are not the same".format(
  783. node, type(node).__name__, repl_node, type(repl_node).__name__
  784. )
  785. # check graph inputs and outputs
  786. for i, n in enumerate(self.outputs):
  787. if n is node:
  788. self.outputs[i] = repl_node
  789. # update users of node and repl_node
  790. # update inputs of expr in node.users
  791. graph = repl_node.top_graph
  792. assert graph is not None
  793. assert graph is self
  794. index = -1
  795. if not isinstance(repl_node.expr, Input):
  796. index = graph._exprs.index(repl_node.expr)
  797. dep_exprs = self.get_dep_exprs(repl_node)
  798. i = 0
  799. while i < len(node.users):
  800. n = node.users[i]
  801. if n in graph._exprs and index >= graph._exprs.index(n):
  802. i += 1
  803. continue
  804. if n in dep_exprs:
  805. logger.info("Find a loop: ignore this replacement once")
  806. logger.info("node: %s" % node.__repr__())
  807. logger.info("expr: %s" % n.__repr__())
  808. i += 1
  809. continue
  810. repl_node.users.append(n)
  811. node.users.pop(i)
  812. idx = n.inputs.index(node)
  813. n.inputs[idx] = repl_node
  814. def _merge_getattr_expr(self):
  815. getattr_nodes_map = dict()
  816. for expr in self._exprs:
  817. if not isinstance(expr, GetAttr):
  818. continue
  819. attr_name = get_suffix_name(self.qualname, expr.outputs[0].qualname)
  820. assert attr_name, '"{}" is not a prefix of "{}"'.format(
  821. self.qualname, expr.outputs[0].qualname
  822. )
  823. if attr_name in getattr_nodes_map:
  824. base_node = getattr_nodes_map[attr_name]
  825. repl_node = expr.outputs[0]
  826. for expr in repl_node.users:
  827. base_node.users.append(expr)
  828. idx = expr.inputs.index(repl_node)
  829. expr.inputs[idx] = base_node
  830. repl_node.users = []
  831. else:
  832. if attr_name != expr.name:
  833. expr.name = attr_name
  834. expr.inputs[0].users.remove(expr)
  835. self.inputs[0].users.append(expr)
  836. expr.inputs[0] = self.inputs[0]
  837. getattr_nodes_map[attr_name] = expr.outputs[0]
  838. def compile(self):
  839. r"""Delete unused expr."""
  840. self._merge_getattr_expr()
  841. dep_exprs = self.get_dep_exprs(self.outputs)
  842. i = 0
  843. while i < len(self._exprs):
  844. expr = self._exprs[i]
  845. if expr in dep_exprs or expr._disable_remove:
  846. i += 1
  847. continue
  848. for n in expr.inputs:
  849. n.users.remove(expr)
  850. self._exprs.remove(expr)
  851. for n in expr.outputs:
  852. self._namespace.unassociate_name_with_obj(n)
  853. def _reset_ids(self):
  854. for total_expr_id, expr in enumerate(self.exprs()):
  855. expr._id = total_expr_id
  856. for total_node_id, node in enumerate(self.nodes()):
  857. node._id = total_node_id
  858. self._total_ids = (total_node_id + 1, total_expr_id + 1)
  859. def _re_associate_name(self):
  860. self._namespace.used_names.clear()
  861. for node in self.nodes(False):
  862. node._name = self._namespace.create_unique_name(node.name, node)
  863. def interpret(self, *inputs):
  864. node2value = {}
  865. end_nodes_set = set(self._end_point)
  866. endnode2value = {}
  867. def get_all_endnode_val(n, v):
  868. if n in end_nodes_set:
  869. endnode2value[n] = v
  870. end_nodes_set.remove(n)
  871. return not end_nodes_set
  872. return False
  873. ref_count = lambda n: len(n.users) + (1 if n in self._outputs else 0)
  874. for n, v in zip(self._inputs, inputs):
  875. if ref_count(n) > 0:
  876. node2value[n] = [v, ref_count(n)]
  877. if n in self._watch_point:
  878. self._rst[n].append(v)
  879. if n in self._end_point and get_all_endnode_val(n, v):
  880. return list(endnode2value[i] for i in self._end_point)
  881. for expr in self._exprs:
  882. values = expr.interpret(*list(node2value[i][0] for i in expr.inputs))
  883. for n in expr.inputs:
  884. node2value[n][1] -= 1
  885. if node2value[n][1] == 0:
  886. node2value.pop(n)
  887. if values is not None:
  888. for n, v in zip(expr.outputs, values):
  889. if ref_count(n) > 0:
  890. node2value[n] = [v, ref_count(n)]
  891. if n in self._watch_point:
  892. self._rst[n] = v
  893. if self._end_point and get_all_endnode_val(n, v):
  894. return list(endnode2value[i] for i in self._end_point)
  895. return list(node2value[i][0] for i in self._outputs)
  896. def eval(self, *inputs: Tuple[Tensor]):
  897. r"""Call this method to execute the graph.
  898. Args:
  899. inputs: the tensors corresponding to the ``graph.inputs[1:]``.
  900. """
  901. assert len(inputs) == len(self._inputs) - 1
  902. inp = [self._inputs[0].owner] + list(inputs)
  903. return self.interpret(*inp)
  904. def __repr__(self):
  905. return self.__format__()
  906. def __format__(self, format_spec: str = "") -> str:
  907. saved_format_spec = Node._set_format_spec(format_spec)
  908. name = ""
  909. if self._name:
  910. name = "%s.Graph" % self._name
  911. res = "{} ({}) {{\n\t{}\n\treturn {}\n}}".format(
  912. name,
  913. ", ".join(str(i) for i in self._inputs),
  914. "\n\t".join("{}".format(str(i)) for i in self._exprs),
  915. ", ".join(str(i) for i in self._outputs),
  916. )
  917. Node._set_format_spec(saved_format_spec)
  918. return res
  919. def __getstate__(self):
  920. state = self.__dict__.copy()
  921. if "_top_graph" in state:
  922. state.pop("_top_graph")
  923. return state
  924. def __setstate__(self, state):
  925. old_version = False
  926. if "_module_name" in state:
  927. old_version = True
  928. state["_qualname"] = state.pop("_module_name")
  929. prefix_name = state.pop("_prefix_name")
  930. if prefix_name:
  931. state["_name"] = "{}_{}".format(prefix_name, state["_name"])
  932. self.__dict__.update(state)
  933. if old_version:
  934. self.inputs[0]._qualname = self._qualname
  935. for e in self.exprs(False):
  936. if isinstance(e, GetAttr):
  937. e.outputs[0]._qualname = "{}.{}".format(
  938. e.inputs[0]._qualname, e.name
  939. )
  940. for n in self.nodes(False):
  941. if isinstance(n.expr, CallMethod) and isinstance(
  942. n.expr.inputs[0], ModuleNode
  943. ):
  944. n._qualname = n.expr.inputs[0]._qualname + ".[out]"
  945. continue
  946. if (
  947. not isinstance(n.expr, GetAttr)
  948. and isinstance(n, TensorNode)
  949. and n._qualname
  950. ):
  951. n._qualname = "{}.{}".format(self._qualname, n._qualname)
  952. self._namespace = NameSpace(self._name, self._qualname)
  953. self._re_associate_name()
  954. def _get_meth_name(obj, func):
  955. tp = obj if isinstance(obj, type) else type(obj)
  956. for cls in tp.mro():
  957. for k, v in cls.__dict__.items():
  958. if v == func:
  959. return k
  960. return None
  961. def _wrapped_function(orig_func):
  962. @functools.wraps(orig_func)
  963. def wrapped_fn(*args, **kwargs):
  964. method_func = wrapped_fn
  965. if "method_func" in kwargs:
  966. method_func = kwargs.pop("method_func")
  967. if is_tracing_module():
  968. unset_module_tracing()
  969. inputs, tree_def = tree_flatten((args, kwargs))
  970. for i in inputs:
  971. if not NodeMixin.get(i, None):
  972. if isinstance(i, (RawTensor, NodeMixin)):
  973. NodeMixin.wrap_safe(i, Constant.make(i))
  974. meth_name, arg_type = None, None
  975. if args:
  976. meth_name = _get_meth_name(args[0], method_func)
  977. arg_type = args[0] if isinstance(args[0], type) else type(args[0])
  978. if meth_name and arg_type and issubclass(arg_type, RawTensor):
  979. self = inputs[0]
  980. if meth_name == "__new__":
  981. if all([not isinstance(i, RawTensor) for i in inputs]):
  982. # only trace Tensor.__new__() when there are tensors in args
  983. set_module_tracing()
  984. return orig_func(*args, **kwargs)
  985. if isinstance(args[1], RawTensor):
  986. node = NodeMixin.get(inputs[1])
  987. inputs[1] = copy.copy(inputs[1])
  988. # copy inputs[1] to avoid tensor and Tensor(tensor) share same m_tensor,
  989. # which will cause they have same _NodeMixin__node in tracing.
  990. NodeMixin.wrap_safe(inputs[1], node)
  991. args, kwargs = tree_def.unflatten(inputs)
  992. call_node = CallMethod.make(self, meth_name)
  993. else:
  994. call_node = CallMethod.make(NodeMixin.get(self), meth_name)
  995. call_node.add_inputs(inputs[1:])
  996. else:
  997. call_node = CallFunction.make(orig_func)
  998. call_node.add_inputs(inputs)
  999. call_node.arg_def = tree_def
  1000. rst = orig_func(*args, **kwargs)
  1001. if meth_name == "__setitem__":
  1002. rst = self
  1003. if rst is not None:
  1004. outputs, out_def = tree_flatten(rst, is_leaf=_is_leaf)
  1005. call_node.out_def = out_def
  1006. else:
  1007. outputs = None
  1008. call_node.add_outputs(outputs)
  1009. set_module_tracing()
  1010. return rst
  1011. return orig_func(*args, **kwargs)
  1012. return wrapped_fn
  1013. class TracedModuleBuilder(NodeMixin):
  1014. _mod = None # type: Module
  1015. _body = None # type: InternalGraph
  1016. _is_builtin = None # type: bool
  1017. _argdef_graph_map = None # type: Dict[Treedef, "InternalGraph"]
  1018. _argdef_outdef_map = None # type: Dict[Treedef, Treedef]
  1019. nodes = None
  1020. __builder_attributes__ = [
  1021. "_mod",
  1022. "_body",
  1023. "_NodeMixin__node",
  1024. "_is_builtin",
  1025. "build",
  1026. "_record_wrapped_nodes",
  1027. "_argdef_graph_map",
  1028. "_argdef_outdef_map",
  1029. "nodes",
  1030. "__class__",
  1031. "__dict__",
  1032. ]
  1033. def __init__(self, mod, is_top_module=False):
  1034. super(TracedModuleBuilder, self).__init__()
  1035. assert isinstance(mod, Module)
  1036. self._mod = mod
  1037. self._body = None
  1038. self._is_top = is_top_module
  1039. self._is_builtin = (
  1040. True
  1041. if isinstance(mod, (Observer, _FakeQuantize))
  1042. else module_tracer.is_builtin(mod)
  1043. )
  1044. if isinstance(self._mod, QATModule):
  1045. unset_module_tracing()
  1046. self._check_qat_module(self._mod)
  1047. set_module_tracing()
  1048. self._argdef_graph_map = {}
  1049. self._argdef_outdef_map = {}
  1050. self.nodes = set()
  1051. # 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__.
  1052. # modify self.__class__ and let the builder inherit from TracedModuleBuilder and mod.__class__.
  1053. self.__class__ = type(
  1054. "TracedModuleBuilder",
  1055. (TracedModuleBuilder, mod.__class__),
  1056. dict(TracedModuleBuilder.__dict__),
  1057. )
  1058. def _check_qat_module(self, qat_module):
  1059. def isbuiltin(m):
  1060. return m is None or module_tracer.is_builtin(m)
  1061. if qat_module.with_act:
  1062. act_observer = qat_module.act_observer
  1063. act_fakequant = qat_module.act_fake_quant
  1064. if not isbuiltin(act_observer) or not isbuiltin(act_fakequant):
  1065. qparams = (
  1066. act_observer.get_qparams()
  1067. if hasattr(act_observer, "get_qparams")
  1068. else act_fakequant.get_qparams()
  1069. )
  1070. dtype = (
  1071. act_observer.dtype
  1072. if hasattr(act_observer, "dtype")
  1073. else act_fakequant.dtype
  1074. )
  1075. qat_module.act_observer = None
  1076. qat_module.act_fake_quant = TM_FakeQuant(dtype)
  1077. qat_module.act_fake_quant.set_qparams(qparams)
  1078. if qat_module.with_weight:
  1079. weight_observer = qat_module.weight_observer
  1080. weight_fakequant = qat_module.weight_fake_quant
  1081. if not isbuiltin(weight_observer) or not isbuiltin(weight_fakequant):
  1082. qparams = (
  1083. weight_observer.get_qparams()
  1084. if hasattr(weight_observer, "get_qparams")
  1085. else weight_fakequant.get_qparams()
  1086. )
  1087. dtype = (
  1088. weight_observer.dtype
  1089. if hasattr(weight_observer, "dtype")
  1090. else weight_fakequant.dtype
  1091. )
  1092. qat_module.weight_observer = None
  1093. qat_module.weight_fake_quant = TM_FakeQuant(dtype)
  1094. qat_module.weight_fake_quant.set_qparams(qparams)
  1095. def build(self):
  1096. if self._is_builtin or isinstance(self._mod, TracedModule):
  1097. if module_tracer.is_builtin(self._mod) or isinstance(
  1098. self._mod, TracedModule
  1099. ):
  1100. mod_type = type(self._mod)
  1101. else:
  1102. assert isinstance(self._mod, (Observer, _FakeQuantize))
  1103. mod_type = (
  1104. Observer if isinstance(self._mod, Observer) else _FakeQuantize
  1105. )
  1106. for node in self.nodes:
  1107. node.module_type = mod_type
  1108. return self._mod
  1109. else:
  1110. is_qat = isinstance(self._mod, QATModule)
  1111. traced_module = TracedModule(
  1112. self._is_top, self._argdef_graph_map, self._argdef_outdef_map, is_qat
  1113. )
  1114. for _, g in self._argdef_graph_map.items():
  1115. g.compile()
  1116. if self._is_top:
  1117. g._total_ids = (Node._get_next_id(), Expr._get_next_id())
  1118. for k, v in self.__dict__.items():
  1119. if k not in TracedModuleBuilder.__builder_attributes__:
  1120. if isinstance(v, TracedModuleBuilder):
  1121. v = v.build()
  1122. setattr(traced_module, k, v)
  1123. elif isinstance(v, RawTensor):
  1124. setattr(traced_module, k, v)
  1125. if isinstance(self._mod, QATModule):
  1126. unset_module_tracing()
  1127. traced_module.with_act = self._mod.with_act
  1128. traced_module.with_weight = self._mod.with_weight
  1129. if not hasattr(traced_module, "act_fake_quant"):
  1130. traced_module.act_fakequant = None
  1131. if not hasattr(traced_module, "act_observer"):
  1132. traced_module.act_observer = None
  1133. if not hasattr(traced_module, "weight_fake_quant"):
  1134. traced_module.weight_fakequant = None
  1135. if not hasattr(traced_module, "weight_observer"):
  1136. traced_module.weight_observer = None
  1137. set_module_tracing()
  1138. return traced_module
  1139. def _record_wrapped_nodes(self, node):
  1140. self.nodes.add(node)
  1141. def __call__(self, *args, **kwargs):
  1142. assert isinstance(self._mod, Module)
  1143. # prepare args and kwargs for inner graph
  1144. if "method_func" in kwargs:
  1145. kwargs.pop("method_func")
  1146. def mark_constant(x):
  1147. node = NodeMixin.get(x, None)
  1148. if node is None: # capture as constant
  1149. NodeMixin.wrap(x, lambda: Constant.make(x))
  1150. inputs, tree_def = tree_flatten(((self, *args), kwargs))
  1151. for i in inputs:
  1152. mark_constant(i)
  1153. callnode = CallMethod.make(NodeMixin.get(self))
  1154. callnode.add_inputs(inputs[1:])
  1155. callnode.arg_def = tree_def
  1156. if (
  1157. self._is_builtin
  1158. or tree_def in self._argdef_graph_map
  1159. or isinstance(self._mod, TracedModule)
  1160. ):
  1161. unset_module_tracing()
  1162. rst = self._mod(*args, **kwargs)
  1163. outputs, out_def = tree_flatten(rst, is_leaf=_is_leaf)
  1164. set_module_tracing()
  1165. if self._is_builtin:
  1166. self._body = None
  1167. elif tree_def in self._argdef_graph_map:
  1168. self._body = self._argdef_graph_map[tree_def]
  1169. else:
  1170. self._mod._is_top = False
  1171. self._body = self._mod.argdef_graph_map[tree_def]
  1172. module_qualname = NodeMixin.get(self).qualname
  1173. if module_qualname != self._body.qualname:
  1174. src_name, dst_name = self._body.qualname, module_qualname
  1175. def replace_qualname(g):
  1176. attr_name = get_suffix_name(src_name, g.qualname)
  1177. if attr_name is not None:
  1178. g._qualname = (
  1179. ("%s.%s" % (dst_name, attr_name))
  1180. if attr_name
  1181. else dst_name
  1182. )
  1183. assert get_suffix_name(dst_name, g.qualname) is not None
  1184. for mod in self._mod.modules():
  1185. if not hasattr(mod, "argdef_graph_map"):
  1186. continue
  1187. for g in mod.argdef_graph_map.values():
  1188. replace_qualname(g)
  1189. g._namespace.qualname = g.qualname
  1190. for n in g.nodes(False):
  1191. replace_qualname(n)
  1192. else:
  1193. self_node = None
  1194. orig_self = NodeMixin.get(self)
  1195. parent_graph = active_module_tracer().current_scope()
  1196. module_qualname = orig_self._qualname
  1197. self._body = InternalGraph(
  1198. name=parent_graph._namespace.create_unique_name(module_qualname),
  1199. qualname=module_qualname,
  1200. )
  1201. parent_graph._namespace.associate_name_with_obj(self._body.name, self._body)
  1202. active_module_tracer().push_scope(self._body)
  1203. # rebind self to new input node
  1204. if self_node:
  1205. NodeMixin.wrap_safe(self, self_node)
  1206. active_module_tracer().current_scope()._add_input(self_node)
  1207. else:
  1208. NodeMixin.wrap_safe(
  1209. self,
  1210. self_node
  1211. if self_node
  1212. else Input.make(
  1213. name="self",
  1214. qualname=module_qualname,
  1215. type=NodeMixin.get_wrapped_type(self),
  1216. ),
  1217. )
  1218. origin_inp_node = [NodeMixin.get(i, None) for i in inputs[1:]]
  1219. # prepare args and kwargs for inner graph
  1220. index_args, index_kwargs = tree_def.unflatten(
  1221. [
  1222. ArgsIndex(0),
  1223. *list(ArgsIndex(i + 1) for i in range(len(origin_inp_node))),
  1224. ]
  1225. )
  1226. key2idx = getcallargs(type(self._mod).forward, *index_args, **index_kwargs)
  1227. idx2key = {}
  1228. for k, v in key2idx.items():
  1229. if isinstance(v, ArgsIndex):
  1230. idx2key[v.index] = k
  1231. else:
  1232. flatten_argidx, _ = tree_flatten(v)
  1233. for _i, v in enumerate(flatten_argidx):
  1234. if isinstance(v, ArgsIndex):
  1235. idx2key[v.index] = k + "_%d" % _i
  1236. def wrap(x, name):
  1237. if isinstance(x, (RawTensor, NodeMixin)):
  1238. NodeMixin.wrap(
  1239. x,
  1240. lambda: Input.make(
  1241. type=NodeMixin.get_wrapped_type(x),
  1242. name=name,
  1243. qualname="%s.[%s]" % (module_qualname, name),
  1244. ),
  1245. )
  1246. return x
  1247. args = [self]
  1248. for i, v in enumerate(inputs[1:]):
  1249. args.append(wrap(v, idx2key[i + 1]))
  1250. args, kwargs = tree_def.unflatten(args)
  1251. active_module_tracer().patcher.auto_patch(
  1252. getattr(getattr(self._mod, "forward", self._mod), "__globals__", {})
  1253. )
  1254. rst = type(self._mod).forward(*args, **kwargs)
  1255. if _convert_node_flag():
  1256. rst = _node_to_tensor(rst)[0][0]
  1257. outputs, out_def = tree_flatten(rst, is_leaf=_is_leaf)
  1258. for i in (
  1259. outputs if isinstance(outputs, collections.abc.Sequence) else (outputs,)
  1260. ):
  1261. mark_constant(i)
  1262. active_module_tracer().current_scope()._add_output(NodeMixin.get(i))
  1263. NodeMixin.wrap_safe(self, orig_self)
  1264. for arg, node in zip(inputs[1:], origin_inp_node):
  1265. if node:
  1266. NodeMixin.wrap_safe(arg, node)
  1267. active_module_tracer().pop_scope()
  1268. # rebind output to outer graph
  1269. callnode.out_def = out_def
  1270. callnode.add_outputs(outputs)
  1271. self._argdef_graph_map[callnode.arg_def] = self._body
  1272. self._argdef_outdef_map[callnode.arg_def] = out_def
  1273. return rst
  1274. def __setattr__(self, name, value):
  1275. object.__setattr__(self, name, value)
  1276. def __repr__(self):
  1277. return repr(self._mod)
  1278. def __getattr__(self, name):
  1279. if name not in self._mod.__dict__:
  1280. attr = getattr(type(self._mod), name).__get__(self, type(self))
  1281. else:
  1282. attr = getattr(self._mod, name)
  1283. if (
  1284. isinstance(attr, FunctionType)
  1285. and id(attr) in active_module_tracer().patcher.patched_fn_ids
  1286. ):
  1287. return active_module_tracer().patcher.wrap_fn(attr)
  1288. if isinstance(attr, (List, Dict)):
  1289. flag = _set_convert_node_flag(False)
  1290. unset_module_tracing()
  1291. has_module, m_container = replace_container_with_module_container(attr)
  1292. if m_container:
  1293. attr = m_container
  1294. if has_module and not m_container:
  1295. raise ValueError(
  1296. "Can not trace the module that uses the same container to store"
  1297. " Module and Non-Module objects."
  1298. )
  1299. set_module_tracing()
  1300. _set_convert_node_flag(flag)
  1301. if isinstance(attr, Module):
  1302. attr = TracedModuleBuilder(attr)
  1303. if isinstance(attr, (Module, RawTensor)):
  1304. setattr(self, name, attr)
  1305. NodeMixin.wrap(
  1306. attr,
  1307. lambda: GetAttr.make(
  1308. NodeMixin.get(self),
  1309. type=NodeMixin.get_wrapped_type(attr),
  1310. attr_name=name,
  1311. name="",
  1312. ),
  1313. )
  1314. return attr
  1315. def __getattribute__(self, name):
  1316. if name in TracedModuleBuilder.__builder_attributes__:
  1317. return object.__getattribute__(self, name)
  1318. else:
  1319. wrapped = object.__getattribute__(self, name)
  1320. class_members = dict(inspect.getmembers(self.__class__))
  1321. if name in self._mod.__dict__:
  1322. mod_attr = getattr(self._mod, name)
  1323. if name in class_members:
  1324. if (
  1325. not isinstance(wrapped, TracedModuleBuilder)
  1326. and wrapped is not mod_attr
  1327. ):
  1328. wrapped = self.__getattr__(name)
  1329. if isinstance(wrapped, TracedModuleBuilder):
  1330. if not isinstance(mod_attr, (List, Dict)):
  1331. assert mod_attr is wrapped._mod
  1332. else:
  1333. assert mod_attr is wrapped
  1334. if isinstance(wrapped, (NodeMixin, RawTensor)):
  1335. NodeMixin.wrap(
  1336. wrapped,
  1337. lambda: GetAttr.make(
  1338. NodeMixin.get(self),
  1339. type=NodeMixin.get_wrapped_type(wrapped),
  1340. attr_name=name,
  1341. name="",
  1342. ),
  1343. )
  1344. return wrapped
  1345. class _expr_iter:
  1346. def __init__(self, graph: InternalGraph, recursive: bool = True):
  1347. self.graph = graph
  1348. self.recursive = recursive
  1349. self._visited_graph = set()
  1350. def __iter__(self):
  1351. for inp_node in self.graph.inputs:
  1352. yield inp_node.expr
  1353. for expr in self.graph._exprs:
  1354. if isinstance(expr, CallMethod) and isinstance(expr.inputs[0], ModuleNode):
  1355. yield expr
  1356. if (
  1357. self.recursive
  1358. and expr.graph is not None
  1359. and id(expr.graph) not in self._visited_graph
  1360. ):
  1361. yield from expr.graph.exprs(self.recursive)
  1362. self._visited_graph.add(id(expr.graph))
  1363. else:
  1364. yield expr
  1365. class _node_iter:
  1366. def __init__(self, graph: InternalGraph, recursive: bool = True) -> None:
  1367. nodes = []
  1368. node_ids = set()
  1369. for expr in graph.exprs(recursive):
  1370. for n in expr.outputs:
  1371. assert id(n) not in node_ids
  1372. nodes.append(n)
  1373. node_ids.add(id(n))
  1374. self.nodes = nodes
  1375. def __iter__(self):
  1376. for node in self.nodes:
  1377. yield node
  1378. class BaseFilter:
  1379. r"""``BaseFilter`` exposes some methods for converting ``_node_iter/_expr_iter`` to ``list``, ``dict``, etc."""
  1380. def __init__(self, iter: Iterable):
  1381. self._iter = iter
  1382. def __iter__(self):
  1383. return iter(self._iter)
  1384. def as_list(self):
  1385. r"""Consume this iterator and return its content as a list.
  1386. Returns:
  1387. A list of ``Node`` or ``Expr``.
  1388. """
  1389. return list(self)
  1390. def as_dict(self):
  1391. r"""Construct an ordered dict to map from ``id`` to objects in this iterator.
  1392. Returns:
  1393. An :class:`OrderedDict`.
  1394. """
  1395. return collections.OrderedDict((i._id, i) for i in self)
  1396. def as_unique(self):
  1397. """Assert that this iterator yields only one ``Node`` or ``Expr`` and return it.
  1398. Rerurns:
  1399. A ``Node`` or ``Expr``.
  1400. """
  1401. rst = self.as_list()
  1402. assert len(rst) == 1, "{} elements found".format(len(rst))
  1403. (elem,) = self
  1404. return elem
  1405. def as_count(self):
  1406. r"""Consume this iterator and get the number of elements."""
  1407. return sum(1 for _ in self)
  1408. class ExprFilter(BaseFilter):
  1409. """Filter on Expr iterator.
  1410. This class is an iterator of :class:`.Expr` objects and multiple
  1411. filtering conditions and mappers can be chained.
  1412. """
  1413. def call_function(self, func):
  1414. r"""Filter by specific ``CallFunction.func``.
  1415. See :meth:`~.InternalGraph.get_function_by_type` for details.
  1416. """
  1417. return ExprFilterCallFunction(self, func)
  1418. def call_method(self, method):
  1419. r"""Filter by specific ``CallMethod.method``.
  1420. See :meth:`~.InternalGraph.get_function_by_type` for details.
  1421. """
  1422. return ExprFilterCallMethod(self, method)
  1423. def expr_id(self, expr_id: List[int]):
  1424. r"""Filter Exprs by their ``id``.
  1425. See :meth:`~.InternalGraph.get_function_by_type` for details.
  1426. """
  1427. return ExprFilterExprId(self, expr_id)
  1428. class NodeFilter(BaseFilter):
  1429. """Filter on Node iterator.
  1430. This class is an iterator of :class:`.Node` objects and multiple
  1431. filtering conditions and mappers can be chained.
  1432. """
  1433. def type(self, owner_type):
  1434. r"""Filter by specific Module type.
  1435. See :meth:`~.InternalGraph.get_module_by_type` for details.
  1436. """
  1437. return NodeFilterType(self, owner_type)
  1438. def node_id(self, node_id: List[int]):
  1439. r"""Filter Nodes by their ``id``.
  1440. See :meth:`~.InternalGraph.get_node_by_id` for details.
  1441. """
  1442. return NodeFilterNodeId(self, node_id)
  1443. def name(self, name: str, ignorecase: bool = True):
  1444. r"""Filter Nodes by their full name.
  1445. See :meth:`~.InternalGraph.get_node_by_name` for details.
  1446. """
  1447. return NodeFilterName(self, name, ignorecase)
  1448. class NodeFilterType(NodeFilter):
  1449. """See :meth:`~.InternalGraph.get_module_by_type`"""
  1450. def __init__(self, expr_iter, owner_type):
  1451. super().__init__(expr_iter)
  1452. self.owner_type = owner_type
  1453. def __iter__(self):
  1454. for node in self._iter:
  1455. if not isinstance(node, ModuleNode):
  1456. continue
  1457. if not hasattr(node, "owner"):
  1458. continue
  1459. if isinstance(node.owner, self.owner_type):
  1460. yield node
  1461. class NodeFilterNodeId(NodeFilter):
  1462. """See :meth:`~.InternalGraph.get_node_by_id`"""
  1463. def __init__(self, expr_iter, node_id: List[int]):
  1464. super().__init__(expr_iter)
  1465. if not isinstance(node_id, Sequence):
  1466. node_id = [node_id]
  1467. self.node_id = node_id
  1468. def __iter__(self):
  1469. for node in self._iter:
  1470. if node._id in self.node_id:
  1471. yield node
  1472. class NodeFilterName(NodeFilter):
  1473. """See :meth:`~.InternalGraph.get_node_by_name`"""
  1474. _re = None
  1475. def __init__(self, node_iter, pattern, ignorecase):
  1476. super().__init__(node_iter)
  1477. self.pattern = pattern
  1478. self._re = self.make_re(pattern, ignorecase)
  1479. @classmethod
  1480. def make_re(cls, pattern, ignorecase=True):
  1481. assert isinstance(pattern, str), "bad pattern: {!r}".format(pattern)
  1482. assert isinstance(ignorecase, bool)
  1483. flags = 0
  1484. if ignorecase:
  1485. flags |= re.IGNORECASE
  1486. return re.compile(fnmatch.translate(pattern), flags=flags)
  1487. def __iter__(self):
  1488. for i in self._iter:
  1489. graph = i.top_graph
  1490. name = "{}_{}".format(graph._name, i._name)
  1491. if self.pattern == name or self._re.match(name):
  1492. yield i
  1493. class ExprFilterCallFunction(ExprFilter):
  1494. """See :meth:`~.InternalGraph.get_function_by_type`"""
  1495. def __init__(self, expr_iter, func: Callable = None):
  1496. super().__init__(expr_iter)
  1497. self.func = func
  1498. def __iter__(self):
  1499. for expr in self._iter:
  1500. if not isinstance(expr, CallFunction):
  1501. continue
  1502. if self.func is None or expr.func == self.func:
  1503. yield expr
  1504. class ExprFilterCallMethod(ExprFilter):
  1505. """See :meth:`~.InternalGraph.get_method_by_type`"""
  1506. def __init__(self, expr_iter, method: str = None):
  1507. super().__init__(expr_iter)
  1508. self.method = method
  1509. def __iter__(self):
  1510. for expr in self._iter:
  1511. if not isinstance(expr, CallMethod):
  1512. continue
  1513. if self.method is None or expr.method == self.method:
  1514. yield expr
  1515. class ExprFilterExprId(ExprFilter):
  1516. """See :meth:`~.InternalGraph.get_expr_by_id`"""
  1517. def __init__(self, expr_iter, expr_id: List[int]):
  1518. super().__init__(expr_iter)
  1519. if not isinstance(expr_id, Sequence):
  1520. expr_id = [expr_id]
  1521. self.expr_id = expr_id
  1522. def __iter__(self):
  1523. for expr in self._iter:
  1524. if expr._id in self.expr_id:
  1525. yield expr
  1526. class TracedModule(Module):
  1527. r"""``TracedModule`` is the Module created by tracing normal module.
  1528. It owns an argdef to graph(InternalGraph) map. The forward method of ``TracedModule``
  1529. will get a graph from ``argdef_graph_map`` according to the argdef of input ``args/kwargs``
  1530. and interpret it.
  1531. .. note::
  1532. ``TracedModule`` can only be created by :func:`~.trace_module`. See :func:`~.trace_module`
  1533. for more details.
  1534. """
  1535. # m_node = None # type: ModuleNode
  1536. argdef_graph_map = None
  1537. argdef_outdef_map = None
  1538. def __init__(self, is_top, argdef_graph_map, argdef_outdef_map, is_qat=False):
  1539. super(TracedModule, self).__init__()
  1540. self.argdef_graph_map = argdef_graph_map
  1541. self.argdef_outdef_map = argdef_outdef_map
  1542. self._is_top = is_top
  1543. self.watch_points = []
  1544. self.watch_node_value = {}
  1545. self.end_points = []
  1546. self.is_qat = is_qat
  1547. def forward(self, *args, **kwargs):
  1548. inputs, treedef = tree_flatten(((self, *args), kwargs))
  1549. assert treedef in self.argdef_graph_map
  1550. inputs = filter(
  1551. lambda i: isinstance(i, (Module, TracedModuleBuilder, RawTensor)), inputs
  1552. ) # allow TracedModuleBuilder for retrace.
  1553. outputs = self.argdef_graph_map[treedef].interpret(*inputs)
  1554. if self.watch_points:
  1555. self.watch_node_value = {}
  1556. for n in self.watch_points:
  1557. self.watch_node_value[n] = n.top_graph._rst.pop(n)
  1558. if self.end_points:
  1559. return outputs
  1560. out_def = self.argdef_outdef_map[treedef]
  1561. outputs = out_def.unflatten(outputs)
  1562. return outputs
  1563. def set_watch_points(self, nodes):
  1564. r"""Initialize the :attr:`~.TracedModule.watch_points`.
  1565. You can call this function to get the ``Tensor/Module`` corresponding to a ``Node`` at runtime.
  1566. Args:
  1567. nodes: a list of ``Node``.
  1568. For example, the following code
  1569. .. code-block::
  1570. import megengine.module as M
  1571. import megengine as mge
  1572. import megengine.traced_module as tm
  1573. class MyModule(M.Module):
  1574. def forward(self, x):
  1575. x = x + 1 + 2
  1576. return x
  1577. net = MyModule()
  1578. inp = mge.Tensor([0])
  1579. traced_module = tm.trace_module(net, inp)
  1580. add_1_node = traced_module.graph.get_node_by_id(2).as_unique()
  1581. traced_module.set_watch_points(add_1_node)
  1582. out = traced_module(inp)
  1583. Will get the following ``watch_node_value``::
  1584. print(traced_module.watch_node_value)
  1585. .. code-block:: text
  1586. {add_out: Tensor([1.], device=xpux:0)}
  1587. """
  1588. if not isinstance(nodes, Sequence):
  1589. nodes = [nodes]
  1590. self.watch_points = nodes
  1591. if nodes:
  1592. nodes[0].top_graph._watch_point = []
  1593. for n in nodes:
  1594. n.top_graph._watch_point.append(n)
  1595. def clear_watch_points(self):
  1596. r"""Clear the :attr:`~.TracedModule.watch_points` and :attr:`~.TracedModule.watch_node_value`.
  1597. """
  1598. for n in self.watch_points:
  1599. n.top_graph._watch_point = []
  1600. self.watch_points = []
  1601. self.watch_node_value = {}
  1602. def set_end_points(self, nodes: Sequence[Node]):
  1603. r"""Initialize the :attr:`~.TracedModule.end_points`.
  1604. When all the ``nodes`` are generated, the Module will stop execution and return directly.
  1605. Args:
  1606. nodes: a list of ``Node``.
  1607. For example, the following code
  1608. .. code-block::
  1609. import megengine.module as M
  1610. import megengine as mge
  1611. import megengine.traced_module as tm
  1612. class MyModule(M.Module):
  1613. def forward(self, x):
  1614. x = x + 1 + 2
  1615. return x
  1616. net = MyModule()
  1617. inp = mge.Tensor([0])
  1618. traced_module = tm.trace_module(net, inp)
  1619. add_1_node = traced_module.graph.get_node_by_id(2).as_unique()
  1620. traced_module.set_end_points(add_1_node)
  1621. out = traced_module(inp)
  1622. Will get the following ``out``::
  1623. print(out)
  1624. .. code-block:: text
  1625. [Tensor([1.], device=xpux:0)]
  1626. """
  1627. if not isinstance(nodes, Sequence):
  1628. nodes = [nodes]
  1629. self.end_points = nodes
  1630. graphs = list(self.argdef_graph_map.values())
  1631. for n in nodes:
  1632. assert n.top_graph in graphs
  1633. n.top_graph._end_point.append(n)
  1634. def clear_end_points(self):
  1635. r"""Clear the :attr:`~.TracedModule.end_points`.
  1636. """
  1637. for n in self.end_points:
  1638. n.top_graph._end_point = []
  1639. self.end_points = []
  1640. @property
  1641. def graph(self) -> InternalGraph:
  1642. """Return the ``InternalGraph`` of this ``TracedModule``.
  1643. """
  1644. if self._is_top:
  1645. self._update_ref()
  1646. assert len(self.argdef_graph_map) == 1
  1647. return list(self.argdef_graph_map.values())[0]
  1648. def _update_ref(self, actual_node_map: Union[Dict] = None, top_graph=None):
  1649. for inp_def, graph in self.argdef_graph_map.items():
  1650. if top_graph is not None:
  1651. graph._top_graph = weakref.ref(top_graph)
  1652. for n in graph._inputs + graph.outputs:
  1653. n._top_graph = weakref.ref(graph)
  1654. graph._inputs[0]._owner = weakref.ref(self)
  1655. for i, n in enumerate(graph._inputs):
  1656. n.actual_node = []
  1657. if actual_node_map is not None and inp_def in actual_node_map.keys():
  1658. n.actual_node = list(list(zip(*(actual_node_map[inp_def])))[i])
  1659. node2obj = {}
  1660. next_actual_node_map = collections.defaultdict(
  1661. lambda: collections.defaultdict(list)
  1662. )
  1663. node2obj[graph._inputs[0]] = self
  1664. for expr in graph._exprs:
  1665. for n in expr.inputs + expr.outputs:
  1666. n._top_graph = weakref.ref(graph)
  1667. expr._top_graph = weakref.ref(graph)
  1668. if isinstance(expr, GetAttr) and isinstance(
  1669. expr.outputs[0], ModuleNode
  1670. ):
  1671. obj = expr.interpret(node2obj[expr.inputs[0]])[0]
  1672. expr.outputs[0]._owner = weakref.ref(obj)
  1673. node2obj[expr.outputs[0]] = obj
  1674. if isinstance(expr, Constant) and isinstance(
  1675. expr.outputs[0], ModuleNode
  1676. ):
  1677. obj = expr.value
  1678. expr.outputs[0]._owner = weakref.ref(obj)
  1679. node2obj[expr.outputs[0]] = obj
  1680. if (
  1681. isinstance(expr, CallMethod)
  1682. and expr.method == "__call__"
  1683. and isinstance(expr.inputs[0], ModuleNode)
  1684. ):
  1685. obj = node2obj[expr.inputs[0]]
  1686. if expr.arg_def is not None:
  1687. next_actual_node_map[obj][expr.arg_def].append(expr.inputs)
  1688. for obj in node2obj.values():
  1689. if obj is self:
  1690. continue
  1691. mnode_map = None
  1692. if obj in next_actual_node_map.keys():
  1693. mnode_map = next_actual_node_map[obj]
  1694. if isinstance(obj, TracedModule):
  1695. obj._update_ref(mnode_map, graph)
  1696. def flatten(self):
  1697. r"""Get a new TracedModule, which eliminates ``GetAttr`` and has no hierarchy.
  1698. Retruns:
  1699. A new :class:`TracedModule`.
  1700. """
  1701. new_module = copy.deepcopy(self)
  1702. def _replace_inputs_and_outputs(expr: Expr, repl_dict: Dict[Node, Node]):
  1703. inputs, outputs = expr.inputs, expr.outputs
  1704. for i, node in enumerate(inputs):
  1705. if node in repl_dict:
  1706. inputs[i] = repl_dict[node]
  1707. for i, node in enumerate(outputs):
  1708. if node in repl_dict:
  1709. outputs[i] = repl_dict[node]
  1710. outputs[i].expr = expr
  1711. def _flatten_subgraph(
  1712. parent_graph: InternalGraph,
  1713. graph: InternalGraph,
  1714. call: CallMethod,
  1715. module: Module,
  1716. ):
  1717. repl_dict, node2obj, rename_blacklist = {}, {}, []
  1718. if call is not None:
  1719. graph = copy.deepcopy(graph)
  1720. node2obj[call.inputs[0]] = module
  1721. repl_dict = dict(zip(graph._inputs, call.inputs))
  1722. for ind, out in enumerate(graph.outputs):
  1723. if isinstance(out.expr, Input):
  1724. assert out in repl_dict
  1725. call_out = call.outputs[ind]
  1726. for expr in call.outputs[ind].users:
  1727. for index, inp in enumerate(expr.inputs):
  1728. if inp is call_out:
  1729. expr.inputs[index] = repl_dict[out]
  1730. repl_dict[out].users.append(expr)
  1731. if parent_graph is not None:
  1732. for index, parent_out in enumerate(parent_graph._outputs):
  1733. if parent_out is call_out:
  1734. parent_graph._outputs[index] = repl_dict[out]
  1735. continue
  1736. repl_dict[out] = call.outputs[ind]
  1737. if isinstance(out, TensorNode):
  1738. call.outputs[ind]._qualname = out._qualname
  1739. for node, repl_node in repl_dict.items():
  1740. assert node in graph._inputs or node in graph._outputs
  1741. repl_node.users.extend(node.users)
  1742. rename_blacklist = list(chain(call.inputs, call.outputs))
  1743. node2obj[graph._inputs[0]] = module
  1744. prefix_name = call.inputs[0]._name if call else ""
  1745. flattened_exprs = []
  1746. for expr in graph._exprs:
  1747. exprs = [expr]
  1748. if call is not None:
  1749. _replace_inputs_and_outputs(expr, repl_dict)
  1750. if isinstance(expr, GetAttr):
  1751. mnode = expr.inputs[0]
  1752. node2obj[expr.outputs[0]] = expr.interpret(node2obj[mnode])[0]
  1753. if isinstance(expr, CallMethod):
  1754. obj_node = expr.inputs[0]
  1755. if isinstance(obj_node, ModuleNode) and isinstance(
  1756. obj_node.expr, GetAttr
  1757. ):
  1758. obj = node2obj[obj_node]
  1759. expr_graph = (
  1760. obj.argdef_graph_map[expr.arg_def]
  1761. if hasattr(obj, "argdef_graph_map")
  1762. else None
  1763. )
  1764. if expr_graph is not None:
  1765. exprs = _flatten_subgraph(graph, expr_graph, expr, obj)
  1766. if parent_graph is not None:
  1767. for node in expr.outputs:
  1768. name = node._name
  1769. if node not in rename_blacklist:
  1770. name = "{}_{}".format(prefix_name, name)
  1771. node._name = parent_graph._namespace.create_unique_name(
  1772. name, node
  1773. )
  1774. flattened_exprs.extend(exprs)
  1775. if call is not None:
  1776. for i in call.inputs:
  1777. i.users.remove(call)
  1778. return flattened_exprs
  1779. new_module.graph._exprs = _flatten_subgraph(
  1780. None, new_module.graph, None, new_module
  1781. )
  1782. new_module.graph._re_associate_name()
  1783. new_module.graph.compile()
  1784. new_module.graph._reset_ids()
  1785. return new_module
  1786. def __getstate__(self):
  1787. d = self.__dict__
  1788. for k in Module.__dict__:
  1789. d.pop(k, None)
  1790. return d
  1791. def cpp_apply_module_trace(opdef, *args):
  1792. return Apply.apply_module_trace_hook(opdef, *args)
  1793. def register_as_builtin(mod_cls: Type[Module]) -> None:
  1794. r"""Registers class ``mod_cls`` (subclass of :class:`~.Module`) as builtin module.
  1795. Args:
  1796. mod_cls: the module class which will be treated as builtin module in tracing.
  1797. """
  1798. module_tracer.register_as_builtin(mod_cls)
  1799. def wrap(func: Callable):
  1800. r"""Call this function to register ``func`` as a builtin function.
  1801. This function can be called at module-level scope to register ``func`` as a builtin function.
  1802. A builtin function will be converted to a :class:`CallFunction` Expr in tracing::
  1803. def my_func(x, y):
  1804. return x + y
  1805. import megengine.traced_module as tm
  1806. tm.wrap(my_func)
  1807. This function can also equivalently be used as a decorator::
  1808. @tm.wrap
  1809. def my_func(x, y):
  1810. return x + y
  1811. Args:
  1812. func: the function of the global function to insert into the graph when it's called.
  1813. """
  1814. assert callable(func), "func must be a callable"
  1815. assert hasattr(func, "__code__")
  1816. fn_name = func.__code__.co_name
  1817. currentframe = inspect.currentframe()
  1818. assert currentframe is not None
  1819. f = currentframe.f_back
  1820. assert f is not None
  1821. assert (
  1822. f.f_code.co_name == "<module>"
  1823. ), "wrap must be called at the top level of a module"
  1824. Patcher._builtin_functions.append((f.f_globals, fn_name))
  1825. return func
  1826. def _register_all_builtin_module():
  1827. for sub_mod in [M, M.qat, M.quantized]:
  1828. for m in getmembers(sub_mod):
  1829. if (
  1830. isclass(m[1])
  1831. and issubclass(m[1], M.Module)
  1832. and m[1] is not M.Sequential
  1833. ):
  1834. module_tracer.register_as_builtin(m[1])
  1835. module_tracer.register_as_builtin(Observer)
  1836. module_tracer.register_as_builtin(MinMaxObserver)
  1837. module_tracer.register_as_builtin(SyncMinMaxObserver)
  1838. module_tracer.register_as_builtin(ExponentialMovingAverageObserver)
  1839. module_tracer.register_as_builtin(SyncExponentialMovingAverageObserver)
  1840. module_tracer.register_as_builtin(HistogramObserver)
  1841. module_tracer.register_as_builtin(PassiveObserver)
  1842. module_tracer.register_as_builtin(LSQ)
  1843. module_tracer.register_as_builtin(TQT)
  1844. module_tracer.register_as_builtin(FakeQuantize)
  1845. module_tracer.register_as_builtin(TM_FakeQuant)
  1846. def trace_module(
  1847. mod: Module, *args: Tuple[Any], **kwargs: Dict[str, Any]
  1848. ) -> TracedModule:
  1849. r"""Traces module ``mod`` and returns corresponding :class:`TracedModule`.
  1850. Args:
  1851. mod: the module will be converted to :class:`TracedModule`.
  1852. args: the positional arguments passed to forward method of ``mod``.
  1853. kwargs: the keyword arguments passed to forward method of ``mod``.
  1854. """
  1855. assert active_module_tracer() is None
  1856. assert isinstance(mod, Module)
  1857. try:
  1858. net_name = mod._name if mod._name else mod.__class__.__name__
  1859. use_sym_shape = set_symbolic_shape(True)
  1860. set_module_tracing()
  1861. set_active_module_tracer(module_tracer(_wrapped_function))
  1862. for cls in [Expr, Node]:
  1863. cls._set_next_id(0)
  1864. with active_module_tracer().patcher:
  1865. global_scope = InternalGraph(name="top", qualname=net_name)
  1866. active_module_tracer().push_scope(global_scope)
  1867. builder = TracedModuleBuilder(mod, True)
  1868. NodeMixin.wrap_safe(
  1869. builder, Input.make(name="top", type=ModuleNode, qualname=net_name)
  1870. )
  1871. inputs, _ = tree_flatten((args, kwargs))
  1872. for _, i in enumerate(inputs):
  1873. # assert isinstance(i, Tensor), "not support "
  1874. if isinstance(i, RawTensor):
  1875. NodeMixin.wrap_safe(
  1876. i,
  1877. Input.make(
  1878. name="arg_{}".format(_),
  1879. type=NodeMixin.get_wrapped_type(i),
  1880. qualname="{}.[{}]".format(net_name, "arg_{}".format(_)),
  1881. ),
  1882. )
  1883. builder(*args, **kwargs)
  1884. active_module_tracer().pop_scope()
  1885. traced_mod = builder.build()
  1886. traced_mod.graph._reset_ids()
  1887. return traced_mod
  1888. finally:
  1889. set_symbolic_shape(use_sym_shape)
  1890. set_active_module_tracer(None)
  1891. unset_module_tracing()

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