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

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

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