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

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

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