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

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

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