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

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

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