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

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

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