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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  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 .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. ovars = G.apply_normal_varnode(op, *ivars)
  532. if require_links and len(ovars) > 0:
  533. io_links = (ovars[0],)
  534. assert len(ovars) == len(ohandles)
  535. for h, v in zip(ohandles, ovars):
  536. info = self._tinfo[h]
  537. info.varnode = v
  538. def add_reader(opnode):
  539. nonlocal in_out_links
  540. need_reset_nodes.append(opnode)
  541. readers.append(opnode.outputs[0])
  542. in_out_links = opnode.outputs
  543. if info.data_read:
  544. # Shape can be obtained from data so doesn't need its own
  545. # output node. On the other hand, value is read separately
  546. # to leverage eager h2d copy
  547. info.shape_read = False
  548. opnode = info.data_reader = G.OutputNode(v, *in_out_links)
  549. add_reader(opnode)
  550. if info.value_read:
  551. opnode = info.value_reader = G.ValueOutputNode(v, *in_out_links)
  552. add_reader(opnode)
  553. if info.shape_read:
  554. opnode = info.shape_reader = G.AttrOutputNode(v, *in_out_links)
  555. add_reader(opnode)
  556. graph.options.graph_opt_level = self._graph_opt_level
  557. graph._set_priority_to_id([*readers, *in_out_links, *io_links])
  558. graph.compile(*readers, *in_out_links, *io_links)
  559. def _reset_exec_env(self):
  560. for opnode in self._need_reset_nodes:
  561. opnode.reset()
  562. def __call__(self, *args, **kwargs):
  563. with self._setup():
  564. if self._capture_as_const:
  565. self._process_inputs(*args, **kwargs)
  566. outputs = self.__wrapped__(*args, **kwargs)
  567. if self._capture_as_const:
  568. self._process_outputs(outputs)
  569. return outputs
  570. def dump(
  571. self,
  572. file,
  573. *,
  574. arg_names=None,
  575. output_names=None,
  576. append=False,
  577. keep_var_name: int = 1,
  578. keep_opr_name: bool = False,
  579. keep_param_name: bool = False,
  580. keep_opr_priority: bool = False,
  581. strip_info_file=None,
  582. append_json=False,
  583. optimize_for_inference=True,
  584. **kwargs
  585. ):
  586. r"""
  587. Serializes trace to file system.
  588. :param file: output file, could be file object or filename.
  589. :param arg_names: names of the input tensors in the traced function.
  590. :param output_names: names of the output tensors in the traced function,
  591. use the default name if not specified.
  592. :param append: whether output is appended to ``file``.
  593. Only works when ``file`` is str.
  594. :param keep_var_name: level for keeping variable names:
  595. * 0: none of the names are kept
  596. * 1: (default)keep names of output vars
  597. * 2: keep names of all (output and internal) vars
  598. :param keep_opr_name: whether to keep operator names.
  599. :param keep_param_name: whether to keep param names, so param values can be
  600. easily manipulated after loading model
  601. :param keep_opr_priority: whether to keep priority setting for operators
  602. :param strip_info_file: a string for path or a file handler. if is not None,
  603. then the dump information for code strip would be written to ``strip_info_file``
  604. :param append_json: will be check when `strip_info_file` is not None. if set
  605. true, the information for code strip will be append to strip_info_file.
  606. if set false, will rewrite strip_info_file
  607. :param optimize_for_inference: enbale optmizations,
  608. will skip all optimize options if this is False. Default: True
  609. :Keyword Arguments:
  610. * enable_io16xc32 --
  611. whether to use float16 for I/O between oprs and use
  612. float32 as internal computation precision. Note the output var would be
  613. changed to float16.
  614. * enable_ioc16 --
  615. whether to use float16 for both I/O and computation
  616. precision.
  617. * enable_hwcd4 --
  618. whether to use NHWCD4 data layout. This is faster on some
  619. OpenCL backend.
  620. * enable_nchw88 --
  621. whether to use NCHW88 data layout, currently
  622. used in X86 AVX backend.
  623. * enable_nchw44 --
  624. whether to use NCHW44 data layout, currently
  625. used in arm backend.
  626. * enable_nchw44_dot --
  627. whether to use NCHW44_dot data layout, currently
  628. used in armv8.2+dotprod backend.
  629. * enable_nchw4 --
  630. whether to use NCHW4 data layout, currently
  631. used in nvidia backend(based on cudnn).
  632. * enable_nchw32 --
  633. whether to use NCHW32 data layout, currently
  634. used in nvidia backend with tensorcore(based on cudnn).
  635. * enable_chwn4 --
  636. whether to use CHWN4 data layout, currently
  637. used in nvidia backend with tensorcore.
  638. * enable_fuse_conv_bias_nonlinearity: whether to fuse conv+bias+nonlinearty
  639. into one opr.
  640. * enable_fuse_conv_bias_with_z: whether to fuse conv_bias with z
  641. input for inference on nvidia backend(this optimization pass will
  642. result in mismatch of the precision of output of training and
  643. inference)
  644. """
  645. if not self._capture_as_const:
  646. raise ValueError(
  647. "you must specify capture_as_const=True at __init__ to use dump"
  648. )
  649. if self._untraced:
  650. raise RuntimeError("should run at least once before calling dump")
  651. if self._output_names and output_names:
  652. raise TypeError(
  653. "cannot specify output_names when output is already in dict format"
  654. )
  655. if output_names and not isinstance(output_names, collections.abc.Sequence):
  656. output_names = (output_names,)
  657. if output_names and len(output_names) != len(self._output_bindings):
  658. raise ValueError(
  659. "wrong number of output_names, should be {} values".format(
  660. len(self._output_bindings)
  661. )
  662. )
  663. without_arg_names = arg_names is None
  664. if without_arg_names:
  665. arg_names = ["arg_%d" % i for i in range(len(self._arg_bindings))]
  666. if arg_names and not isinstance(arg_names, collections.abc.Sequence):
  667. arg_names = (arg_names,)
  668. if arg_names and len(arg_names) != len(self._arg_bindings):
  669. raise ValueError(
  670. "wrong number of arg_names, should be {} values".format(
  671. len(self._arg_bindings)
  672. )
  673. )
  674. output_names = output_names or self._output_names
  675. def dumped_device(info):
  676. device_name = info.device.logical_name
  677. if device_name[:3] in ("cpu", "gpu", "xpu"):
  678. return as_device("xpux")
  679. return info.device
  680. h2v = {}
  681. graph = G.Graph()
  682. # apply graph_opt_level in dump
  683. if self._graph_opt_level is not None:
  684. graph.options.graph_opt_level = self._graph_opt_level
  685. for i, h in enumerate(self._arg_bindings):
  686. info = self._tinfo[h]
  687. h2v[h] = graph.make_h2d(
  688. dtype=info.dtype,
  689. device=dumped_device(info),
  690. shape=info.shape or (1,),
  691. name=info.name if without_arg_names and info.name else arg_names[i],
  692. )
  693. for k, h in self._kwarg_bindings.items():
  694. info = self._tinfo[h]
  695. h2v[h] = graph.make_h2d(
  696. dtype=info.dtype,
  697. device=dumped_device(info),
  698. shape=info.shape or (1,),
  699. name=k,
  700. )
  701. for op, ihandles, ohandles in self._seq:
  702. if isinstance(op, str) and op == "Const":
  703. assert len(ihandles) == 0
  704. (h,) = ohandles
  705. info = self._tinfo[h]
  706. if h not in h2v:
  707. assert info.external
  708. assert info.bound_data
  709. h2v[h] = graph.make_const(
  710. info.bound_data.numpy(),
  711. dtype=info.dtype,
  712. device=info.device,
  713. name=info.name,
  714. )
  715. continue
  716. ivars = []
  717. for h in ihandles:
  718. info = self._tinfo[h]
  719. if h not in h2v:
  720. assert info.external
  721. assert info.bound_data
  722. h2v[h] = graph.make_const(
  723. info.bound_data.numpy(),
  724. dtype=info.dtype,
  725. device=dumped_device(info),
  726. name=info.name,
  727. )
  728. ivars.append(h2v[h])
  729. if isinstance(op, BatchNorm):
  730. assert (
  731. op.fwd_mode == BatchNorm.FwdMode.INFERENCE
  732. ), "can not dump BatchNorm in training mode, maybe you forget to do model.eval()?"
  733. ovars = G.apply_normal_varnode(op, *ivars)
  734. AutoNaming.record_opnode(ovars[0].op)
  735. assert len(ovars) == len(ohandles)
  736. h2v.update(zip(ohandles, ovars))
  737. for i in ohandles:
  738. name = AutoNaming.get_var_name(i)
  739. if name is not None:
  740. h2v[i].name = name
  741. AutoNaming.remove_duplicate_names()
  742. dest_vars = []
  743. for i, h in enumerate(self._output_bindings):
  744. v = h2v[h]
  745. if output_names:
  746. v.name = output_names[i]
  747. dest_vars.append(v)
  748. if optimize_for_inference:
  749. dest_vars = G.optimize_for_inference(dest_vars, **kwargs)
  750. if isinstance(file, str):
  751. permission = "wb" if append == False else "ab"
  752. file = open(file, permission)
  753. dump_content, dump_info = G.dump_graph(
  754. dest_vars,
  755. keep_var_name=keep_var_name,
  756. keep_opr_name=keep_opr_name,
  757. keep_param_name=keep_param_name,
  758. keep_opr_priority=keep_opr_priority,
  759. strip_info_file=strip_info_file,
  760. append_json=append_json,
  761. )
  762. file.write(dump_content)
  763. return dump_info
  764. def _process_inputs(self, *args, **kwargs):
  765. if self._untraced:
  766. self._inputs_to_restore = []
  767. def record_input(x):
  768. if x is None:
  769. return
  770. h, info = self._new_handle()
  771. info.external = False
  772. info.name = x.c_name
  773. info.device = x.device
  774. info.dtype = x.dtype
  775. info.shape = x.numpy().shape
  776. x._mixin_handle = h
  777. x._recording = True
  778. x._trace_mixin_info = info
  779. self._inputs_to_restore.append(x)
  780. return h
  781. self._arg_bindings = []
  782. for i, x in enumerate(args):
  783. if not isinstance(x, RawTensor):
  784. raise TypeError(
  785. "positional arguments should all be tensor "
  786. "but args[%d] cannot be recognized as one" % i
  787. )
  788. self._arg_bindings.append(record_input(x))
  789. self._kwarg_bindings = {}
  790. for k, x in kwargs.items():
  791. if isinstance(x, RawTensor):
  792. self._kwarg_bindings[k] = record_input(x)
  793. else:
  794. if len(args) != len(self._arg_bindings):
  795. raise TraceMismatchError("positional argument length mismatch")
  796. self._tensor_remaps = {}
  797. for i, (h, x) in enumerate(zip(self._arg_bindings, args)):
  798. if not isinstance(x, RawTensor):
  799. raise TypeError(
  800. "positional arguments should all be tensor "
  801. "but args[%d] cannot be recognized as one" % i
  802. )
  803. info = self._tinfo[h]
  804. if x.dtype != info.dtype:
  805. raise TypeError("args[%d].dtype different from last time" % i)
  806. if x.device != info.device:
  807. raise TypeError("args[%d].device different from last time" % i)
  808. info.data_setter.set_value(x._dev_tensor())
  809. self._tensor_remaps[x._handle] = CompiledTensorProxy(h)
  810. kwargs_tensors = {}
  811. for k, x in kwargs.items():
  812. if isinstance(x, RawTensor):
  813. kwargs_tensors[k] = x
  814. if set(kwargs_tensors) != set(self._kwarg_bindings):
  815. too_many = set(kwargs_tensors) - set(self._kwarg_bindings)
  816. too_few = set(self._kwarg_bindings) - set(kwargs_tensors)
  817. if too_many:
  818. raise TraceMismatchError(
  819. "keyword arguments found to be tensor this time "
  820. "but were non-tensor previously: %s" % " ".join(too_many)
  821. )
  822. if too_few:
  823. raise TraceMismatchError(
  824. "keyword arguments found to be non-tensor this time "
  825. "but were tensor previously: %s" % " ".join(too_few)
  826. )
  827. for k, h in self._kwarg_bindings.items():
  828. x = kwargs_tensors[k]
  829. info = self._tinfo[h]
  830. if x.dtype != info.dtype:
  831. raise TypeError("kwargs[%s].dtype different from last time" % k)
  832. if x.device != info.device:
  833. raise TypeError("kwargs[%s].device different from last time" % k)
  834. info.data_setter.set_value(x._dev_tensor())
  835. self._tensor_remaps[x._handle] = CompiledTensorProxy(h)
  836. def _process_outputs(self, outputs):
  837. output_names = None
  838. if isinstance(outputs, collections.abc.Mapping):
  839. output_names, outputs = zip(*sorted(outputs.items()))
  840. elif not isinstance(outputs, collections.abc.Sequence):
  841. outputs = (outputs,)
  842. if not self._untraced:
  843. if output_names != self._output_names:
  844. too_many = set(output_names) - set(self._output_names)
  845. too_few = set(self._output_names) - set(output_names)
  846. if too_many:
  847. raise TraceMismatchError(
  848. "output has more keys than last time: %s" % " ".join(too_many)
  849. )
  850. if too_few:
  851. raise TraceMismatchError(
  852. "output has less keys than last time: %s" % " ".join(too_few)
  853. )
  854. if len(outputs) != len(self._output_bindings):
  855. raise TraceMismatchError("output size differs from last time")
  856. else:
  857. self._output_names = output_names
  858. self._output_bindings = []
  859. for i, x in enumerate(outputs):
  860. if not isinstance(x, RawTensor):
  861. raise TypeError("every item of return value should be tensor")
  862. if self._untraced:
  863. h = x._mixin_handle
  864. if h < 0:
  865. raise RuntimeError("output is not computed from inputs")
  866. self._output_bindings.append(h)
  867. else:
  868. h = x._mixin_handle
  869. if h not in self._output_handles:
  870. raise RuntimeError("output is not computed from inputs")
  871. if h != self._output_bindings[i]:
  872. raise TraceMismatchError(
  873. "retval[%s] is a different tensor than last time"
  874. % (output_names and output_names[i] or i)
  875. )
  876. def get_profile(self):
  877. """
  878. Get profiling result for compiled trace.
  879. :return: a json compatible object.
  880. """
  881. if not self._profiler:
  882. raise RuntimeError("trace is not set with profiling=True")
  883. return json.loads(self._profiler.get())
  884. def trace(self, *args, **kwargs):
  885. raise NotImplementedError(
  886. "trace is deemed unbeneficial with the new "
  887. "tracing mechanism. You should alwasy use __call__."
  888. )
  889. class CompiledTensorProxy:
  890. """
  891. Duck-typed RawTensor
  892. """
  893. def __init__(self, handle):
  894. self.__handle = handle
  895. self._isscalar = False
  896. self.__info = active_trace._tinfo[handle]
  897. self.__shape = None
  898. self.__data = None
  899. self.__value = None
  900. @property
  901. def dtype(self):
  902. return self.__info.varnode.dtype
  903. @property
  904. def device(self):
  905. return self.__info.varnode.device
  906. @property
  907. def shape(self):
  908. if self._isscalar:
  909. return ()
  910. if self.__shape is None:
  911. if self.__info.shape_read:
  912. self.__shape = self.__info.shape_reader.get_value().shape
  913. elif self.__info.data_read:
  914. self.__shape = self._dev_tensor().shape
  915. else:
  916. # c++ will throw TraceReadError
  917. return None
  918. return self.__shape
  919. def numpy(self):
  920. if self.__value is None:
  921. if self.__info.value_read:
  922. self.__value = self.__info.value_reader.get_value()
  923. elif self.__info.data_read:
  924. self.__value = self._dev_tensor().numpy()
  925. else:
  926. # c++ will throw TraceReadError
  927. return None
  928. # c++ side will handle scalar case
  929. return self.__value
  930. def _dev_tensor(self):
  931. if self.__data is None:
  932. if not self.__info.data_read:
  933. # c++ will throw TraceReadError
  934. return None
  935. self.__data = self.__info.data_reader.get_value()
  936. return self.__data
  937. def __del__(self):
  938. if self.__info.shape_read and self.__shape is not None:
  939. self.__info.shape_reader.drop_value()
  940. if self.__info.value_read and self.__value is not None:
  941. self.__info.value_reader.drop_value()
  942. if self.__info.data_read and self.__data is not None:
  943. self.__info.data_reader.drop_value()
  944. def assign_raw_tensor(lhs, rhs):
  945. lhs.__init__(rhs)
  946. def apply_symbolic_mode(op: OpDef, *args: RawTensor):
  947. graph = active_trace._lazy_eval_graph
  948. ivars = []
  949. for x in args:
  950. var = getattr(x, "_varnode", None)
  951. if var:
  952. ivars.append(var)
  953. else:
  954. data_setter = G.InputNode(
  955. device=x.device,
  956. dtype=x.dtype,
  957. shape=x.numpy().shape or (1,),
  958. graph=graph,
  959. use_static_shape=True,
  960. )
  961. var = data_setter.outputs[0]
  962. ivars.append(var)
  963. data_setter.set_value(x._dev_tensor())
  964. require_links = type(op) in _io_op_types
  965. if require_links and active_trace._lazy_eval_links:
  966. assert len(ivars) > 0, "op should has at least one input"
  967. opnode = G.VirtualDepNode(
  968. [ivars[0], *active_trace._lazy_eval_links],
  969. str(active_trace._lazy_eval_links[0].device),
  970. )
  971. ivars[0] = opnode.outputs[0]
  972. active_trace._lazy_eval_links = (ivars[0],)
  973. ovars = G.apply_normal_varnode(op, *ivars)
  974. outputs = [RawTensor(o) for o in ovars]
  975. if require_links:
  976. active_trace._lazy_eval_links = (G.VarNode(outputs[0]._varnode),)
  977. return outputs
  978. def apply_const_symbolic_mode(value, dtype, device, name):
  979. graph = active_trace._lazy_eval_graph
  980. # don't need to unset tracing
  981. # because varnode construction will ignore tracing flag
  982. ret = RawTensor(graph.make_const(value, dtype=dtype, device=device, name=name))
  983. if np.array(value).ndim == 0:
  984. setscalar(ret)
  985. return (ret,)
  986. def apply_compiled_mode(op: OpDef, *args: RawTensor):
  987. if skip_tracing:
  988. args = [
  989. RawTensor(x._dev_tensor()) if x.__class__ is CompiledTensorProxy else x
  990. for x in args
  991. ]
  992. unset_tracing()
  993. ret = apply(op, *args)
  994. set_tracing()
  995. return ret
  996. return active_trace._apply_op(op, args)
  997. def apply_const_compiled_mode(value, dtype, device, is_const, no_cache, name):
  998. if skip_tracing:
  999. unset_tracing()
  1000. ret = RawTensor(value, dtype, device, False, name)
  1001. set_tracing()
  1002. return ret
  1003. return active_trace._apply_const(value, dtype, device)
  1004. def apply_with_tracing(op: OpDef, *args: RawTensor):
  1005. if active_trace._graph:
  1006. # if member _graph exits, then is_compiled
  1007. return apply_compiled_mode(op, *args)
  1008. if hasattr(op, "scope"):
  1009. op.scope = AutoNaming.get_scope()
  1010. if active_trace._symbolic:
  1011. outputs = apply_symbolic_mode(op, *args)
  1012. else:
  1013. unset_tracing()
  1014. outputs = apply(op, *args)
  1015. set_tracing()
  1016. active_trace._record_op(op, args, outputs)
  1017. return list(outputs)
  1018. def apply_const_with_tracing(value, dtype, device, is_const, no_cache, name):
  1019. if active_trace._graph:
  1020. return apply_const_compiled_mode(value, dtype, device, is_const, no_cache, name)
  1021. if active_trace._symbolic:
  1022. outputs = apply_const_symbolic_mode(value, dtype, device, name)
  1023. else:
  1024. unset_tracing()
  1025. outputs = RawTensor(value, dtype, device, False, name)
  1026. if np.array(value).ndim == 0:
  1027. setscalar(outputs)
  1028. outputs = (outputs,)
  1029. set_tracing()
  1030. active_trace._record_const(outputs)
  1031. return list(outputs)

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