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.

tracing.py 44 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import collections
  10. import contextlib
  11. import functools
  12. import itertools
  13. import json
  14. import os
  15. import numpy as np
  16. from ..core._imperative_rt import GraphProfiler
  17. from ..core._imperative_rt.core2 import Tensor as RawTensor
  18. from ..core._imperative_rt.core2 import (
  19. TensorWeakRef,
  20. apply,
  21. set_tracing,
  22. skip_tracing,
  23. unset_tracing,
  24. )
  25. from ..core._imperative_rt.ops import (
  26. AssertEqual,
  27. CollectiveComm,
  28. RemoteRecv,
  29. RemoteSend,
  30. )
  31. from ..core._trace_option import set_symbolic_shape
  32. from ..core._wrap import device as as_device
  33. from ..core.ops.builtin import BatchNorm, OpDef
  34. from ..core.ops.special import Const
  35. from ..core.tensor import megbrain_graph as G
  36. from ..core.tensor.utils import setscalar
  37. from ..utils.naming import AutoNaming
  38. from .dtr_config import DTRConfig
  39. from .sublinear_memory_config import SublinearMemoryConfig
  40. def _input_node_use_static_shape():
  41. return os.environ.get("MEGENGINE_INPUT_NODE_USE_STATIC_SHAPE") is not None
  42. class TraceMismatchError(RuntimeError):
  43. pass
  44. active_trace = None
  45. def is_tracing():
  46. if active_trace is None:
  47. return False
  48. else:
  49. return not skip_tracing
  50. @contextlib.contextmanager
  51. def exclude_from_trace():
  52. global skip_tracing
  53. if skip_tracing:
  54. yield
  55. return
  56. try:
  57. skip_tracing = True
  58. unset_tracing()
  59. if active_trace is not None:
  60. active_trace._begin_excluded_region()
  61. yield
  62. finally:
  63. skip_tracing = False
  64. set_tracing()
  65. class TensorInfo:
  66. __slots__ = (
  67. # collected attributes
  68. "name",
  69. "external",
  70. "data_read",
  71. "shape_read",
  72. "value_read",
  73. "exported",
  74. "device",
  75. "dtype",
  76. "shape",
  77. "is_const",
  78. "bound_data",
  79. # resources for execution
  80. "varnode",
  81. "data_setter",
  82. "shape_reader",
  83. "value_reader",
  84. "data_reader",
  85. )
  86. def __init__(self):
  87. self.name = None
  88. self.exported = None
  89. self.data_read = None
  90. self.shape_read = None
  91. self.value_read = None
  92. self.bound_data = None
  93. self.data_setter = None
  94. self.shape_reader = None
  95. self.value_reader = None
  96. self.data_reader = None
  97. _io_op_types = {AssertEqual, CollectiveComm, RemoteSend, RemoteRecv}
  98. class trace:
  99. """
  100. Wraps a callable and provide:
  101. * tracing via :meth:`.trace` and :meth:`.dump`
  102. * accelerated evalutaion via :meth:`.__call__`
  103. :param function: the function will be traced.
  104. :param symbolic: whether to apply symbolic execution for tracing. Default: False
  105. :param capture_as_const: capture global vars or closures as const value. Default: False
  106. :param sublinear_memory_config: configuration for sublinear memory optimization.
  107. If not None, it enables sublinear memory optimization with given setting.
  108. :param profiling: whether to profile compiled trace. Default: False
  109. :param opt_level: optimization level for compiling trace. Default: 2
  110. :param symbolic_shape: whether to use symbolic shape for tracing. Default: True
  111. """
  112. def __new__(cls, *args, **kwargs):
  113. if not args:
  114. return functools.partial(cls, **kwargs)
  115. return super().__new__(cls)
  116. def __init__(
  117. self,
  118. function,
  119. symbolic=False,
  120. capture_as_const=False,
  121. sublinear_memory_config: SublinearMemoryConfig = None,
  122. dtr_config: DTRConfig = None,
  123. profiling: bool = False,
  124. opt_level: int = 2,
  125. symbolic_shape: bool = True,
  126. ):
  127. self.__wrapped__ = function
  128. self._symbolic = symbolic
  129. self._capture_as_const = capture_as_const
  130. self._sublinear_memory_config = sublinear_memory_config
  131. self._dtr_config = dtr_config
  132. self._profiling = profiling
  133. self._profiler = None
  134. self._graph_opt_level = opt_level
  135. self._symbolic_shape = symbolic_shape
  136. self._output_handles = set()
  137. self._reset()
  138. def _reset(self):
  139. self._untraced = True
  140. self._tinfo = [] # handle -> TensorInfo
  141. self._seq = []
  142. self._pc = 0
  143. self._graph = None
  144. self._need_reset_nodes = None
  145. self._lazy_eval_graph = None
  146. self._lazy_eval_tensors = set()
  147. self._lazy_eval_links = None
  148. self._active_tensors = set()
  149. self._tensor_remaps = None
  150. self._inputs_to_restore = None
  151. self._arg_bindings = None
  152. self._kwarg_bindings = None
  153. self._output_bindings = None
  154. self._output_names = None
  155. def _new_handle(self):
  156. handle = len(self._tinfo)
  157. info = TensorInfo()
  158. self._tinfo.append(info)
  159. return handle, info
  160. def _apply_op(self, op, args):
  161. assert not self._untraced
  162. # check against trace
  163. if self._pc >= len(self._seq):
  164. raise TraceMismatchError("trace should end here, but more op observed")
  165. record = self._seq[self._pc]
  166. op_, ihandles, ohandles = record
  167. if (isinstance(op_, str) and op_ == "Const") or (op != op_):
  168. raise TraceMismatchError("op different from last time")
  169. if len(ihandles) != len(args):
  170. raise TraceMismatchError("op input size different from last time")
  171. # check all inputs of crrent op
  172. for h, x in zip(ihandles, args):
  173. info = self._tinfo[h]
  174. if info.external:
  175. if (
  176. x._compiled_info is not None
  177. and not self._tinfo[x._mixin_handle].exported
  178. ):
  179. raise TraceMismatchError(
  180. "failed to capture: input was an external tensor "
  181. "last time, got an internal tensor this time"
  182. )
  183. if info.bound_data:
  184. if x._compiled_info is not None:
  185. raise TraceMismatchError(
  186. "const capture violated: was an external tensor "
  187. "last time, got an internal tensor this time"
  188. )
  189. if x._handle != info.bound_data._handle:
  190. if not np.array_equal(x.numpy(), info.bound_data.numpy()):
  191. raise TraceMismatchError(
  192. "const capture violated: got "
  193. "a different tensor this time"
  194. )
  195. else:
  196. if info.dtype != x.dtype:
  197. raise TraceMismatchError(
  198. "failed to capture: different dtype from last time"
  199. )
  200. if info.device != x.device:
  201. raise TraceMismatchError(
  202. "failed to capture: different device from last time"
  203. )
  204. info.data_setter.set_value(x._dev_tensor())
  205. else:
  206. if x._mixin_handle == -1:
  207. if x._handle not in self._tensor_remaps:
  208. raise TraceMismatchError(
  209. "unexpected capture: trying to use an external tensor as "
  210. "input, but that input was an internal tensor last time"
  211. )
  212. else:
  213. x._mixin_handle = self._tensor_remaps[
  214. x._handle
  215. ]._CompiledTensorProxy__handle
  216. if x._mixin_handle != h:
  217. raise TraceMismatchError(
  218. "mis-wiring: input edge to an data flow "
  219. "graph node is different from last time"
  220. )
  221. self._pc += 1
  222. outputs = []
  223. for h in ohandles:
  224. info = self._tinfo[h]
  225. # generate output tensor and create compied info
  226. y = RawTensor(info.varnode)
  227. y._compiled_info = CompiledTensorProxy(h)
  228. y._mixin_handle = h
  229. outputs += [y]
  230. self._active_tensors.add(TensorWeakRef(y))
  231. self._output_handles.update(ohandles)
  232. return outputs
  233. def _apply_const(self, value, dtype, device):
  234. assert not self._untraced
  235. # check against trace
  236. if self._pc >= len(self._seq):
  237. raise TraceMismatchError("trace should end here, but more op observed")
  238. record = self._seq[self._pc]
  239. op_, ihandles, ohandles = record
  240. # Const op is represented by a str
  241. assert isinstance(op_, str) and op_ == "Const"
  242. eq = np.all(np.atleast_1d(value) == self._tinfo[ohandles[0]].bound_data.numpy())
  243. if not eq:
  244. raise TraceMismatchError(
  245. "const tensor violated: got a different tensor this time"
  246. )
  247. self._pc += 1
  248. (h,) = ohandles
  249. outputs = [self._tinfo[h].bound_data]
  250. return outputs
  251. # run in first step, record information for trace
  252. def _record_op(self, op, inputs, outputs):
  253. if skip_tracing:
  254. for x in inputs:
  255. h = getattr(x, "_mixin_handle", -1)
  256. if h >= 0:
  257. self._tinfo[h].data = True
  258. return
  259. ihandles = []
  260. for x in inputs:
  261. h = getattr(x, "_mixin_handle", -1)
  262. if h < 0 or (not self._capture_as_const and self._tinfo[h].exported):
  263. h, info = self._new_handle()
  264. name = AutoNaming.gen_name(x)
  265. info.name = name
  266. info.external = True
  267. info.device = x.device
  268. info.dtype = x.dtype
  269. info.shape = x.shape
  270. if self._capture_as_const:
  271. info.bound_data = RawTensor(
  272. x.numpy(), x.dtype, x.device, False, name
  273. )
  274. ihandles.append(h)
  275. ohandles = []
  276. for x in outputs:
  277. h, info = self._new_handle()
  278. ohandles.append(h)
  279. info.external = False
  280. x._mixin_handle = h
  281. x._recording = True
  282. x._trace_mixin_info = info
  283. self._active_tensors.add(TensorWeakRef(x))
  284. if self._symbolic:
  285. self._lazy_eval_tensors.add(TensorWeakRef(x))
  286. self._seq.append((op, tuple(ihandles), tuple(ohandles)))
  287. def _record_const(self, outputs):
  288. if skip_tracing:
  289. (x,) = outputs
  290. h = getattr(x, "_mixin_handle", -1)
  291. if h >= 0:
  292. self._tinfo[h].data_read = True
  293. return
  294. (x,) = outputs
  295. h, info = self._new_handle()
  296. ohandles = [h]
  297. info.external = True
  298. info.device = x.device
  299. info.dtype = x.dtype
  300. info.shape = x.shape
  301. info.bound_data = x
  302. info.is_const = True
  303. x._mixin_handle = h
  304. x._recording = True
  305. x._trace_mixin_info = info
  306. if self._symbolic:
  307. self._lazy_eval_tensors.add(TensorWeakRef(x))
  308. self._seq.append(("Const", tuple(), tuple(ohandles)))
  309. def _set_active(self, active: bool):
  310. global active_trace
  311. if active:
  312. if active_trace:
  313. raise NotImplementedError("sorry, not implemented: nested trace")
  314. active_trace = self
  315. else:
  316. assert active_trace is self
  317. active_trace = None
  318. def _init_trace(self, symbolic: bool):
  319. if symbolic:
  320. self._lazy_eval_graph = G.Graph()
  321. self._apply_graph_options(self._lazy_eval_graph)
  322. self._lazy_eval_links = ()
  323. def _take_escaped_tensors(self):
  324. escaped_tensors = tuple(filter(lambda x: x() is not None, self._active_tensors))
  325. self._active_tensors.clear()
  326. return escaped_tensors
  327. def _lazy_eval(self, lazy_eval_graph, lazy_eval_tensors, lazy_eval_links):
  328. lazy_eval_tensors = [x() for x in lazy_eval_tensors]
  329. lazy_eval_tensors = [x for x in lazy_eval_tensors if x is not None]
  330. readers = [G.OutputNode(x._varnode).outputs[0] for x in lazy_eval_tensors]
  331. self._apply_graph_options(lazy_eval_graph)
  332. lazy_eval_graph.options.graph_opt_level = self._graph_opt_level
  333. lazy_eval_graph._set_priority_to_id([*lazy_eval_links, *readers])
  334. lazy_eval_graph.compile(*lazy_eval_links, *readers)
  335. lazy_eval_graph()
  336. for r, x in zip(readers, lazy_eval_tensors):
  337. # get values from lazy_eval_graph and assign to lazy_eval tensor
  338. x._handle = RawTensor(r.op.get_value())._handle
  339. x._reset_varnode()
  340. @contextlib.contextmanager
  341. def _setup(self):
  342. interrupted = False
  343. def do_enter():
  344. set_tracing()
  345. self._save_symbolic_shape = set_symbolic_shape(self._symbolic_shape)
  346. self._set_active(True)
  347. if self._untraced:
  348. self._init_trace(self._symbolic)
  349. else:
  350. if self._graph is None:
  351. self._compile()
  352. self._graph.execute()
  353. def do_finalize():
  354. escaped_tensors = self._take_escaped_tensors()
  355. if self._untraced:
  356. for x in escaped_tensors:
  357. if x():
  358. info = self._tinfo[x()._mixin_handle]
  359. info.data_read = True
  360. x()._mixin_handle = -1
  361. x()._recording = False
  362. if self._inputs_to_restore:
  363. for x in self._inputs_to_restore:
  364. x._mixin_handle = -1
  365. x._recording = False
  366. if self._symbolic and (
  367. self._lazy_eval_tensors or self._lazy_eval_links
  368. ):
  369. # eval lazy eval tensors
  370. self._lazy_eval(
  371. self._lazy_eval_graph,
  372. self._lazy_eval_tensors,
  373. self._lazy_eval_links,
  374. )
  375. self._lazy_eval_graph = None
  376. self._lazy_eval_tensors = None
  377. self._lazy_eval_links = None
  378. self._untraced = False
  379. else:
  380. # compiled_tensor leaks
  381. if self._pc == len(self._seq):
  382. for x in escaped_tensors:
  383. try:
  384. assign_raw_tensor(x(), RawTensor(x()._dev_tensor()))
  385. except RuntimeError:
  386. # TraceMismatchError thrown in do_exit
  387. pass
  388. self._graph.wait()
  389. self._reset_exec_env()
  390. # reset status
  391. self._pc = 0
  392. self._tensor_remaps = None
  393. self._set_active(False)
  394. set_symbolic_shape(self._save_symbolic_shape)
  395. unset_tracing()
  396. def do_exit():
  397. unset_tracing()
  398. if not self._untraced and self._pc != len(self._seq):
  399. raise TraceMismatchError("premature end")
  400. if not self._symbolic or not self._untraced:
  401. # reset output tensors
  402. for x in self._active_tensors.copy():
  403. strong_x = x()
  404. if strong_x is not None:
  405. strong_x._dev_tensor()
  406. strong_x._reset_varnode()
  407. strong_x._mixin_handle = -1
  408. strong_x._recording = False
  409. strong_x._trace_mixin_info = None
  410. try:
  411. do_enter()
  412. yield
  413. do_exit()
  414. except:
  415. interrupted = True
  416. raise
  417. finally:
  418. do_finalize()
  419. if interrupted:
  420. self._reset()
  421. def _begin_excluded_region(self):
  422. if self._capture_as_const:
  423. raise RuntimeError(
  424. "exclude_from_trace cannot be used with capture_as_const"
  425. )
  426. if self._untraced:
  427. # conditionally reading a compiled tensor in excluded region
  428. # is permitted, so we have to assume every tensor might be read
  429. for x in self._active_tensors:
  430. strong_x = x()
  431. if strong_x:
  432. info = self._tinfo[strong_x._mixin_handle]
  433. info.exported = True
  434. info.data_read = True
  435. else:
  436. for x in self._active_tensors:
  437. strong_x = x()
  438. if strong_x:
  439. strong_x._dev_tensor()
  440. def _apply_graph_options(self, graph):
  441. graph.options.no_force_inplace = True
  442. graph.options.seq_opt.enable_seq_comp_node_opt = False
  443. graph.options.graph_opt_level = self._graph_opt_level
  444. if self._dtr_config is not None:
  445. graph.options.enable_dtr_memory_opt = True
  446. graph.options.dtr_config.eviction_threshold = (
  447. self._dtr_config.eviction_threshold
  448. )
  449. graph.options.dtr_config.evictee_minimum_size = (
  450. self._dtr_config.evictee_minimum_size
  451. )
  452. # sublinear
  453. if self._sublinear_memory_config is not None:
  454. graph.options.enable_sublinear_memory_opt = True
  455. sublinear_config = graph.options.sublinear_mem_config
  456. sublinear_config.lb_memory = self._sublinear_memory_config.lb_memory
  457. sublinear_config.genetic_nr_iter = (
  458. self._sublinear_memory_config.genetic_nr_iter
  459. )
  460. sublinear_config.genetic_pool_size = (
  461. self._sublinear_memory_config.genetic_pool_size
  462. )
  463. sublinear_config.thresh_nr_try = self._sublinear_memory_config.thresh_nr_try
  464. sublinear_config.num_worker = self._sublinear_memory_config.num_worker
  465. # profile
  466. if self._profiling:
  467. self._profiler = GraphProfiler(graph)
  468. if int(os.getenv("MEGENGINE_INPLACE_UPDATE", "0")):
  469. graph.options.var_sanity_check_first_run = False
  470. def _compile(self):
  471. graph = self._graph = G.Graph()
  472. graph.options.async_exec_level = 0b100
  473. self._apply_graph_options(graph)
  474. need_reset_nodes = self._need_reset_nodes = []
  475. # links enforce ordering of I/O nodes
  476. in_out_links = ()
  477. io_links = ()
  478. readers = []
  479. if self._capture_as_const:
  480. for h in itertools.chain(self._arg_bindings, self._kwarg_bindings.values()):
  481. info = self._tinfo[h]
  482. opnode = info.data_setter = G.InputNode(
  483. device=info.device,
  484. dtype=info.dtype,
  485. shape=info.shape or (1,),
  486. graph=graph,
  487. use_static_shape=_input_node_use_static_shape(),
  488. )
  489. need_reset_nodes.append(opnode)
  490. info.varnode = opnode.outputs[0]
  491. in_out_links += opnode.outputs[1:]
  492. for op, ihandles, ohandles in self._seq:
  493. if isinstance(op, str) and op == "Const":
  494. assert len(ihandles) == 0
  495. (h,) = ohandles
  496. info = self._tinfo[h]
  497. if not hasattr(info, "varnode"):
  498. assert info.external
  499. assert info.bound_data
  500. info.varnode = graph.make_const(
  501. info.bound_data.numpy(),
  502. info.bound_data.dtype,
  503. info.bound_data.device,
  504. )
  505. continue
  506. require_links = type(op) in _io_op_types
  507. ivars = []
  508. for i, h in enumerate(ihandles):
  509. info = self._tinfo[h]
  510. if not hasattr(info, "varnode"):
  511. assert info.external
  512. if info.bound_data:
  513. if getattr(info, "is_const", False):
  514. info.varnode = graph.make_const(
  515. info.bound_data.numpy(),
  516. info.bound_data.dtype,
  517. info.bound_data.device,
  518. )
  519. else:
  520. info.varnode = graph.make_const(
  521. info.bound_data._dev_tensor()
  522. # info.bound_data.numpy()
  523. )
  524. else:
  525. opnode = info.data_setter = G.InputNode(
  526. *in_out_links,
  527. device=info.device,
  528. dtype=info.dtype,
  529. shape=info.shape or (1,),
  530. graph=graph,
  531. use_static_shape=_input_node_use_static_shape(),
  532. )
  533. need_reset_nodes.append(opnode)
  534. info.varnode, *in_out_links = opnode.outputs
  535. if require_links and i == 0 and len(io_links) > 0:
  536. opnode = G.VirtualDepNode(
  537. [info.varnode, *io_links], str(io_links[0].device)
  538. )
  539. info.varnode = opnode.outputs[0]
  540. io_links = (info.varnode,)
  541. ivars.append(info.varnode)
  542. ovars = G.apply_normal_varnode(op, *ivars)
  543. if require_links and len(ovars) > 0:
  544. io_links = (ovars[0],)
  545. assert len(ovars) == len(ohandles)
  546. for h, v in zip(ohandles, ovars):
  547. info = self._tinfo[h]
  548. info.varnode = v
  549. def add_reader(opnode):
  550. nonlocal in_out_links
  551. need_reset_nodes.append(opnode)
  552. readers.append(opnode.outputs[0])
  553. in_out_links = opnode.outputs
  554. if info.data_read:
  555. # Shape can be obtained from data so doesn't need its own
  556. # output node. On the other hand, value is read separately
  557. # to leverage eager h2d copy
  558. info.shape_read = False
  559. opnode = info.data_reader = G.OutputNode(v, *in_out_links)
  560. add_reader(opnode)
  561. if info.value_read:
  562. opnode = info.value_reader = G.ValueOutputNode(v, *in_out_links)
  563. add_reader(opnode)
  564. if info.shape_read:
  565. opnode = info.shape_reader = G.AttrOutputNode(v, *in_out_links)
  566. add_reader(opnode)
  567. graph.options.graph_opt_level = self._graph_opt_level
  568. graph._set_priority_to_id([*readers, *in_out_links, *io_links])
  569. graph.compile(*readers, *in_out_links, *io_links)
  570. def _reset_exec_env(self):
  571. for opnode in self._need_reset_nodes:
  572. opnode.reset()
  573. def __call__(self, *args, **kwargs):
  574. with self._setup():
  575. if self._capture_as_const:
  576. self._process_inputs(*args, **kwargs)
  577. outputs = self.__wrapped__(*args, **kwargs)
  578. if self._capture_as_const:
  579. self._process_outputs(outputs)
  580. return outputs
  581. def dump(
  582. self,
  583. file,
  584. *,
  585. arg_names=None,
  586. output_names=None,
  587. append=False,
  588. keep_var_name: int = 1,
  589. keep_opr_name: bool = False,
  590. keep_param_name: bool = False,
  591. keep_opr_priority: bool = False,
  592. strip_info_file=None,
  593. append_json=False,
  594. optimize_for_inference=True,
  595. **kwargs
  596. ):
  597. r"""
  598. Serializes trace to file system.
  599. :param file: output file, could be file object or filename.
  600. :param arg_names: names of the input tensors in the traced function.
  601. :param output_names: names of the output tensors in the traced function,
  602. use the default name if not specified.
  603. :param append: whether output is appended to ``file``.
  604. Only works when ``file`` is str.
  605. :param keep_var_name: level for keeping variable names:
  606. * 0: none of the names are kept
  607. * 1: (default)keep names of output vars
  608. * 2: keep names of all (output and internal) vars
  609. :param keep_opr_name: whether to keep operator names.
  610. :param keep_param_name: whether to keep param names, so param values can be
  611. easily manipulated after loading model
  612. :param keep_opr_priority: whether to keep priority setting for operators
  613. :param strip_info_file: a string for path or a file handler. if is not None,
  614. then the dump information for code strip would be written to ``strip_info_file``
  615. :param append_json: will be check when `strip_info_file` is not None. if set
  616. true, the information for code strip will be append to strip_info_file.
  617. if set false, will rewrite strip_info_file
  618. :param optimize_for_inference: enbale optmizations,
  619. will skip all optimize options if this is False. Default: True
  620. :Keyword Arguments:
  621. * enable_io16xc32 --
  622. whether to use float16 for I/O between oprs and use
  623. float32 as internal computation precision. Note the output var would be
  624. changed to float16.
  625. * enable_ioc16 --
  626. whether to use float16 for both I/O and computation
  627. precision.
  628. * enable_hwcd4 --
  629. whether to use NHWCD4 data layout. This is faster on some
  630. OpenCL backend.
  631. * enable_nchw88 --
  632. whether to use NCHW88 data layout, currently
  633. used in X86 AVX backend.
  634. * enable_nchw44 --
  635. whether to use NCHW44 data layout, currently
  636. used in arm backend.
  637. * enable_nchw44_dot --
  638. whether to use NCHW44_dot data layout, currently
  639. used in armv8.2+dotprod backend.
  640. * enable_nchw4 --
  641. whether to use NCHW4 data layout, currently
  642. used in nvidia backend(based on cudnn).
  643. * enable_nchw32 --
  644. whether to use NCHW32 data layout, currently
  645. used in nvidia backend with tensorcore(based on cudnn).
  646. * enable_chwn4 --
  647. whether to use CHWN4 data layout, currently
  648. used in nvidia backend with tensorcore.
  649. * enable_fuse_conv_bias_nonlinearity: whether to fuse conv+bias+nonlinearty
  650. into one opr.
  651. * enable_fuse_conv_bias_with_z: whether to fuse conv_bias with z
  652. input for inference on nvidia backend(this optimization pass will
  653. result in mismatch of the precision of output of training and
  654. inference)
  655. """
  656. if not self._capture_as_const:
  657. raise ValueError(
  658. "you must specify capture_as_const=True at __init__ to use dump"
  659. )
  660. if self._untraced:
  661. raise RuntimeError("should run at least once before calling dump")
  662. if self._output_names and output_names:
  663. raise TypeError(
  664. "cannot specify output_names when output is already in dict format"
  665. )
  666. if output_names and not isinstance(output_names, collections.abc.Sequence):
  667. output_names = (output_names,)
  668. if output_names and len(output_names) != len(self._output_bindings):
  669. raise ValueError(
  670. "wrong number of output_names, should be {} values".format(
  671. len(self._output_bindings)
  672. )
  673. )
  674. without_arg_names = arg_names is None
  675. if without_arg_names:
  676. arg_names = ["arg_%d" % i for i in range(len(self._arg_bindings))]
  677. if arg_names and not isinstance(arg_names, collections.abc.Sequence):
  678. arg_names = (arg_names,)
  679. if arg_names and len(arg_names) != len(self._arg_bindings):
  680. raise ValueError(
  681. "wrong number of arg_names, should be {} values".format(
  682. len(self._arg_bindings)
  683. )
  684. )
  685. output_names = output_names or self._output_names
  686. def dumped_device(info):
  687. device_name = info.device.logical_name
  688. if device_name[:3] in ("cpu", "gpu", "xpu"):
  689. return as_device("xpux")
  690. return info.device
  691. h2v = {}
  692. graph = G.Graph()
  693. # apply graph_opt_level in dump
  694. if self._graph_opt_level is not None:
  695. graph.options.graph_opt_level = self._graph_opt_level
  696. for i, h in enumerate(self._arg_bindings):
  697. info = self._tinfo[h]
  698. h2v[h] = graph.make_h2d(
  699. dtype=info.dtype,
  700. device=dumped_device(info),
  701. shape=info.shape or (1,),
  702. name=info.name if without_arg_names and info.name else arg_names[i],
  703. )
  704. for k, h in self._kwarg_bindings.items():
  705. info = self._tinfo[h]
  706. h2v[h] = graph.make_h2d(
  707. dtype=info.dtype,
  708. device=dumped_device(info),
  709. shape=info.shape or (1,),
  710. name=k,
  711. )
  712. for op, ihandles, ohandles in self._seq:
  713. if isinstance(op, str) and op == "Const":
  714. assert len(ihandles) == 0
  715. (h,) = ohandles
  716. info = self._tinfo[h]
  717. if h not in h2v:
  718. assert info.external
  719. assert info.bound_data
  720. h2v[h] = graph.make_const(
  721. info.bound_data.numpy(),
  722. dtype=info.dtype,
  723. device=info.device,
  724. name=info.name,
  725. )
  726. continue
  727. ivars = []
  728. for h in ihandles:
  729. info = self._tinfo[h]
  730. if h not in h2v:
  731. assert info.external
  732. assert info.bound_data
  733. h2v[h] = graph.make_const(
  734. info.bound_data.numpy(),
  735. dtype=info.dtype,
  736. device=dumped_device(info),
  737. name=info.name,
  738. )
  739. ivars.append(h2v[h])
  740. if isinstance(op, BatchNorm):
  741. assert (
  742. op.fwd_mode == BatchNorm.FwdMode.INFERENCE
  743. ), "can not dump BatchNorm in training mode, maybe you forget to do model.eval()?"
  744. ovars = G.apply_normal_varnode(op, *ivars)
  745. AutoNaming.record_opnode(ovars[0].op)
  746. assert len(ovars) == len(ohandles)
  747. h2v.update(zip(ohandles, ovars))
  748. for i in ohandles:
  749. name = AutoNaming.get_var_name(i)
  750. if name is not None:
  751. h2v[i].name = name
  752. AutoNaming.remove_duplicate_names()
  753. dest_vars = []
  754. for i, h in enumerate(self._output_bindings):
  755. v = h2v[h]
  756. if output_names:
  757. v.name = output_names[i]
  758. dest_vars.append(v)
  759. if optimize_for_inference:
  760. dest_vars = G.optimize_for_inference(dest_vars, **kwargs)
  761. if isinstance(file, str):
  762. permission = "wb" if append == False else "ab"
  763. file = open(file, permission)
  764. dump_content, dump_info = G.dump_graph(
  765. dest_vars,
  766. keep_var_name=keep_var_name,
  767. keep_opr_name=keep_opr_name,
  768. keep_param_name=keep_param_name,
  769. keep_opr_priority=keep_opr_priority,
  770. strip_info_file=strip_info_file,
  771. append_json=append_json,
  772. )
  773. file.write(dump_content)
  774. return dump_info
  775. def _process_inputs(self, *args, **kwargs):
  776. if self._untraced:
  777. self._inputs_to_restore = []
  778. def record_input(x):
  779. if x is None:
  780. return
  781. h, info = self._new_handle()
  782. info.external = False
  783. info.name = x.c_name
  784. info.device = x.device
  785. info.dtype = x.dtype
  786. info.shape = x.numpy().shape
  787. x._mixin_handle = h
  788. x._recording = True
  789. x._trace_mixin_info = info
  790. self._inputs_to_restore.append(x)
  791. return h
  792. self._arg_bindings = []
  793. for i, x in enumerate(args):
  794. if not isinstance(x, RawTensor):
  795. raise TypeError(
  796. "positional arguments should all be tensor "
  797. "but args[%d] cannot be recognized as one" % i
  798. )
  799. self._arg_bindings.append(record_input(x))
  800. self._kwarg_bindings = {}
  801. for k, x in kwargs.items():
  802. if isinstance(x, RawTensor):
  803. self._kwarg_bindings[k] = record_input(x)
  804. else:
  805. if len(args) != len(self._arg_bindings):
  806. raise TraceMismatchError("positional argument length mismatch")
  807. self._tensor_remaps = {}
  808. for i, (h, x) in enumerate(zip(self._arg_bindings, args)):
  809. if not isinstance(x, RawTensor):
  810. raise TypeError(
  811. "positional arguments should all be tensor "
  812. "but args[%d] cannot be recognized as one" % i
  813. )
  814. info = self._tinfo[h]
  815. if x.dtype != info.dtype:
  816. raise TypeError("args[%d].dtype different from last time" % i)
  817. if x.device != info.device:
  818. raise TypeError("args[%d].device different from last time" % i)
  819. info.data_setter.set_value(x._dev_tensor())
  820. self._tensor_remaps[x._handle] = CompiledTensorProxy(h)
  821. kwargs_tensors = {}
  822. for k, x in kwargs.items():
  823. if isinstance(x, RawTensor):
  824. kwargs_tensors[k] = x
  825. if set(kwargs_tensors) != set(self._kwarg_bindings):
  826. too_many = set(kwargs_tensors) - set(self._kwarg_bindings)
  827. too_few = set(self._kwarg_bindings) - set(kwargs_tensors)
  828. if too_many:
  829. raise TraceMismatchError(
  830. "keyword arguments found to be tensor this time "
  831. "but were non-tensor previously: %s" % " ".join(too_many)
  832. )
  833. if too_few:
  834. raise TraceMismatchError(
  835. "keyword arguments found to be non-tensor this time "
  836. "but were tensor previously: %s" % " ".join(too_few)
  837. )
  838. for k, h in self._kwarg_bindings.items():
  839. x = kwargs_tensors[k]
  840. info = self._tinfo[h]
  841. if x.dtype != info.dtype:
  842. raise TypeError("kwargs[%s].dtype different from last time" % k)
  843. if x.device != info.device:
  844. raise TypeError("kwargs[%s].device different from last time" % k)
  845. info.data_setter.set_value(x._dev_tensor())
  846. self._tensor_remaps[x._handle] = CompiledTensorProxy(h)
  847. def _process_outputs(self, outputs):
  848. output_names = None
  849. if isinstance(outputs, collections.abc.Mapping):
  850. output_names, outputs = zip(*sorted(outputs.items()))
  851. elif not isinstance(outputs, collections.abc.Sequence):
  852. outputs = (outputs,)
  853. if not self._untraced:
  854. if output_names != self._output_names:
  855. too_many = set(output_names) - set(self._output_names)
  856. too_few = set(self._output_names) - set(output_names)
  857. if too_many:
  858. raise TraceMismatchError(
  859. "output has more keys than last time: %s" % " ".join(too_many)
  860. )
  861. if too_few:
  862. raise TraceMismatchError(
  863. "output has less keys than last time: %s" % " ".join(too_few)
  864. )
  865. if len(outputs) != len(self._output_bindings):
  866. raise TraceMismatchError("output size differs from last time")
  867. else:
  868. self._output_names = output_names
  869. self._output_bindings = []
  870. for i, x in enumerate(outputs):
  871. if not isinstance(x, RawTensor):
  872. raise TypeError("every item of return value should be tensor")
  873. if self._untraced:
  874. h = x._mixin_handle
  875. if h < 0:
  876. raise RuntimeError("output is not computed from inputs")
  877. self._output_bindings.append(h)
  878. else:
  879. h = x._mixin_handle
  880. if h not in self._output_handles:
  881. raise RuntimeError("output is not computed from inputs")
  882. if h != self._output_bindings[i]:
  883. raise TraceMismatchError(
  884. "retval[%s] is a different tensor than last time"
  885. % (output_names and output_names[i] or i)
  886. )
  887. def get_profile(self):
  888. """
  889. Get profiling result for compiled trace.
  890. :return: a json compatible object.
  891. """
  892. if not self._profiler:
  893. raise RuntimeError("trace is not set with profiling=True")
  894. return json.loads(self._profiler.get())
  895. def trace(self, *args, **kwargs):
  896. raise NotImplementedError(
  897. "trace is deemed unbeneficial with the new "
  898. "tracing mechanism. You should alwasy use __call__."
  899. )
  900. class CompiledTensorProxy:
  901. """
  902. Duck-typed RawTensor
  903. """
  904. def __init__(self, handle):
  905. self.__handle = handle
  906. self._isscalar = False
  907. self.__info = active_trace._tinfo[handle]
  908. self.__shape = None
  909. self.__data = None
  910. self.__value = None
  911. @property
  912. def dtype(self):
  913. return self.__info.varnode.dtype
  914. @property
  915. def device(self):
  916. return self.__info.varnode.device
  917. @property
  918. def shape(self):
  919. if self._isscalar:
  920. return ()
  921. if self.__shape is None:
  922. if self.__info.shape_read:
  923. self.__shape = self.__info.shape_reader.get_value().shape
  924. elif self.__info.data_read:
  925. self.__shape = self._dev_tensor().shape
  926. else:
  927. # c++ will throw TraceReadError
  928. return None
  929. return self.__shape
  930. def numpy(self):
  931. if self.__value is None:
  932. if self.__info.value_read:
  933. self.__value = self.__info.value_reader.get_value()
  934. elif self.__info.data_read:
  935. self.__value = self._dev_tensor().numpy()
  936. else:
  937. # c++ will throw TraceReadError
  938. return None
  939. # c++ side will handle scalar case
  940. return self.__value
  941. def _dev_tensor(self):
  942. if self.__data is None:
  943. if not self.__info.data_read:
  944. # c++ will throw TraceReadError
  945. return None
  946. self.__data = self.__info.data_reader.get_value()
  947. return self.__data
  948. def __del__(self):
  949. if self.__info.shape_read and self.__shape is not None:
  950. self.__info.shape_reader.drop_value()
  951. if self.__info.value_read and self.__value is not None:
  952. self.__info.value_reader.drop_value()
  953. if self.__info.data_read and self.__data is not None:
  954. self.__info.data_reader.drop_value()
  955. def assign_raw_tensor(lhs, rhs):
  956. lhs.__init__(rhs)
  957. def apply_symbolic_mode(op: OpDef, *args: RawTensor):
  958. graph = active_trace._lazy_eval_graph
  959. ivars = []
  960. for x in args:
  961. var = getattr(x, "_varnode", None)
  962. if var:
  963. ivars.append(var)
  964. else:
  965. data_setter = G.InputNode(
  966. device=x.device,
  967. dtype=x.dtype,
  968. shape=x.numpy().shape or (1,),
  969. graph=graph,
  970. use_static_shape=True,
  971. )
  972. var = data_setter.outputs[0]
  973. ivars.append(var)
  974. data_setter.set_value(x._dev_tensor())
  975. require_links = type(op) in _io_op_types
  976. if require_links and active_trace._lazy_eval_links:
  977. assert len(ivars) > 0, "op should has at least one input"
  978. opnode = G.VirtualDepNode(
  979. [ivars[0], *active_trace._lazy_eval_links],
  980. str(active_trace._lazy_eval_links[0].device),
  981. )
  982. ivars[0] = opnode.outputs[0]
  983. active_trace._lazy_eval_links = (ivars[0],)
  984. ovars = G.apply_normal_varnode(op, *ivars)
  985. outputs = [RawTensor(o) for o in ovars]
  986. if require_links:
  987. active_trace._lazy_eval_links = (G.VarNode(outputs[0]._varnode),)
  988. return outputs
  989. def apply_const_symbolic_mode(value, dtype, device, name):
  990. graph = active_trace._lazy_eval_graph
  991. # don't need to unset tracing
  992. # because varnode construction will ignore tracing flag
  993. ret = RawTensor(graph.make_const(value, dtype=dtype, device=device, name=name))
  994. if np.array(value).ndim == 0:
  995. setscalar(ret)
  996. return (ret,)
  997. def apply_compiled_mode(op: OpDef, *args: RawTensor):
  998. if skip_tracing:
  999. args = [
  1000. RawTensor(x._dev_tensor()) if x.__class__ is CompiledTensorProxy else x
  1001. for x in args
  1002. ]
  1003. unset_tracing()
  1004. ret = apply(op, *args)
  1005. set_tracing()
  1006. return ret
  1007. return active_trace._apply_op(op, args)
  1008. def apply_const_compiled_mode(value, dtype, device, is_const, no_cache, name):
  1009. if skip_tracing:
  1010. unset_tracing()
  1011. ret = RawTensor(value, dtype, device, False, name)
  1012. set_tracing()
  1013. return ret
  1014. return active_trace._apply_const(value, dtype, device)
  1015. def apply_with_tracing(op: OpDef, *args: RawTensor):
  1016. if active_trace._graph:
  1017. # if member _graph exits, then is_compiled
  1018. return apply_compiled_mode(op, *args)
  1019. if hasattr(op, "scope"):
  1020. op.scope = AutoNaming.get_scope()
  1021. if active_trace._symbolic:
  1022. outputs = apply_symbolic_mode(op, *args)
  1023. else:
  1024. unset_tracing()
  1025. outputs = apply(op, *args)
  1026. set_tracing()
  1027. active_trace._record_op(op, args, outputs)
  1028. return list(outputs)
  1029. def apply_const_with_tracing(value, dtype, device, is_const, no_cache, name):
  1030. if active_trace._graph:
  1031. return apply_const_compiled_mode(value, dtype, device, is_const, no_cache, name)
  1032. if active_trace._symbolic:
  1033. outputs = apply_const_symbolic_mode(value, dtype, device, name)
  1034. else:
  1035. unset_tracing()
  1036. outputs = RawTensor(value, dtype, device, False, name)
  1037. if np.array(value).ndim == 0:
  1038. setscalar(outputs)
  1039. outputs = (outputs,)
  1040. set_tracing()
  1041. active_trace._record_const(outputs)
  1042. return list(outputs)

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