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 (
  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 = {}
  141. self._lazy_eval_links = None
  142. self._active_tensors = {}
  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._active_tensors[h] = TensorWeakRef(y)
  223. self._output_handles.update(ohandles)
  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._active_tensors[h] = TensorWeakRef(x)
  270. if self._symbolic:
  271. self._lazy_eval_tensors[h] = TensorWeakRef(x)
  272. self._seq.append((op, tuple(ihandles), tuple(ohandles)))
  273. def _record_const(self, outputs):
  274. if skip_tracing:
  275. (x,) = outputs
  276. h = getattr(x, "mixin_handle", -1)
  277. if h >= 0:
  278. self._tinfo[h].data_read = True
  279. return
  280. (x,) = outputs
  281. h, info = self._new_handle()
  282. ohandles = [h]
  283. info.external = True
  284. info.device = x.device
  285. info.dtype = x.dtype
  286. info.shape = x.shape
  287. info.bound_data = x
  288. info.is_const = True
  289. x.mixin_handle = h
  290. x.recording = True
  291. x._trace_mixin_info = info
  292. if self._symbolic:
  293. self._lazy_eval_tensors[h] = TensorWeakRef(x)
  294. self._seq.append(("Const", tuple(), tuple(ohandles)))
  295. def _set_active(self, active: bool):
  296. global active_trace
  297. if active:
  298. if active_trace:
  299. raise NotImplementedError("sorry, not implemented: nested trace")
  300. active_trace = self
  301. else:
  302. assert active_trace is self
  303. active_trace = None
  304. def _init_trace(self, symbolic: bool):
  305. if symbolic:
  306. self._lazy_eval_graph = G.Graph()
  307. self._apply_graph_options(self._lazy_eval_graph)
  308. self._lazy_eval_links = ()
  309. def _take_escaped_tensors(self):
  310. escaped_tensors = tuple(filter(lambda x: x() is not None, self._active_tensors.values()))
  311. self._active_tensors.clear()
  312. return escaped_tensors
  313. def _lazy_eval(self, lazy_eval_graph, lazy_eval_tensors, lazy_eval_links):
  314. lazy_eval_tensors = list(filter(lambda x: x() is not None, lazy_eval_tensors.values()))
  315. readers = [G.OutputNode(x()._varnode).outputs[0] for x in lazy_eval_tensors]
  316. self._apply_graph_options(lazy_eval_graph)
  317. # FIXME
  318. if self._graph_opt_level is not None:
  319. lazy_eval_graph.options.graph_opt_level = self._graph_opt_level
  320. else:
  321. lazy_eval_graph.options.graph_opt_level = 2
  322. lazy_eval_graph._set_priority_to_id([*lazy_eval_links, *readers])
  323. lazy_eval_graph.compile(*lazy_eval_links, *readers)
  324. lazy_eval_graph()
  325. for r, x in zip(readers, lazy_eval_tensors):
  326. x()._handle = RawTensor(r.op.get_value())._handle
  327. x()._reset_varnode()
  328. @contextlib.contextmanager
  329. def _setup(self):
  330. interrupted = False
  331. def do_enter():
  332. set_tracing()
  333. self._save_symbolic_shape = set_symbolic_shape(self._symbolic_shape)
  334. self._set_active(True)
  335. if self._untraced:
  336. self._init_trace(self._symbolic)
  337. else:
  338. set_compiled()
  339. if self._graph is None:
  340. self._compile()
  341. self._graph.execute()
  342. def do_finalize():
  343. escaped_tensors = self._take_escaped_tensors()
  344. if self._untraced:
  345. for x in escaped_tensors:
  346. if x():
  347. info = self._tinfo[x().mixin_handle]
  348. info.data_read = True
  349. x().mixin_handle = -1
  350. x().recording = False
  351. if self._inputs_to_restore:
  352. for x in self._inputs_to_restore:
  353. x.mixin_handle = -1
  354. x.recording = False
  355. if self._symbolic and (
  356. self._lazy_eval_tensors or self._lazy_eval_links
  357. ):
  358. # eval lazy eval tensors
  359. self._lazy_eval(
  360. self._lazy_eval_graph,
  361. self._lazy_eval_tensors,
  362. self._lazy_eval_links,
  363. )
  364. self._lazy_eval_graph = None
  365. self._lazy_eval_tensors = None
  366. self._lazy_eval_links = None
  367. self._untraced = False
  368. else:
  369. # compiled_tensor leaks
  370. if self._pc == len(self._seq):
  371. for x in escaped_tensors:
  372. try:
  373. assign_raw_tensor(x(), RawTensor(x()._dev_tensor()))
  374. except RuntimeError:
  375. # TraceMismatchError thrown in do_exit
  376. pass
  377. self._graph.wait()
  378. self._reset_exec_env()
  379. # reset status
  380. self._pc = 0
  381. self._tensor_remaps = None
  382. self._set_active(False)
  383. set_symbolic_shape(self._save_symbolic_shape)
  384. unset_compiled()
  385. unset_tracing()
  386. def do_exit():
  387. unset_tracing()
  388. if not self._untraced and self._pc != len(self._seq):
  389. raise TraceMismatchError("premature end")
  390. if not self._symbolic or not self._untraced:
  391. for x in self._active_tensors.values():
  392. if x() is not None:
  393. x()._dev_tensor()
  394. x()._reset_varnode()
  395. x().mixin_handle = -1
  396. x().recording = False
  397. try:
  398. do_enter()
  399. yield
  400. do_exit()
  401. except:
  402. interrupted = True
  403. raise
  404. finally:
  405. do_finalize()
  406. if interrupted:
  407. self._reset()
  408. def _begin_excluded_region(self):
  409. if self._capture_as_const:
  410. raise RuntimeError(
  411. "exclude_from_trace cannot be used with capture_as_const"
  412. )
  413. if self._untraced:
  414. # conditionally reading a compiled tensor in excluded region
  415. # is permitted, so we have to assume every tensor might be read
  416. for x in self._active_tensors.values():
  417. info = self._tinfo[x().mixin_handle]
  418. info.exported = True
  419. info.data_read = True
  420. x()._dev_tensor()
  421. def _apply_graph_options(self, graph):
  422. graph.options.no_force_inplace = True
  423. graph.options.seq_opt.enable_seq_comp_node_opt = False
  424. # graph opt level
  425. # if self._graph_opt_level is not None:
  426. # graph.options.graph_opt_level = self._graph_opt_level
  427. # FIXME
  428. graph.options.graph_opt_level = 0
  429. # sublinear
  430. if self._sublinear_memory_config is not None:
  431. graph.options.enable_sublinear_memory_opt = True
  432. sublinear_config = graph.options.sublinear_mem_config
  433. sublinear_config.lb_memory = self._sublinear_memory_config.lb_memory
  434. sublinear_config.genetic_nr_iter = (
  435. self._sublinear_memory_config.genetic_nr_iter
  436. )
  437. sublinear_config.genetic_pool_size = (
  438. self._sublinear_memory_config.genetic_pool_size
  439. )
  440. sublinear_config.thresh_nr_try = self._sublinear_memory_config.thresh_nr_try
  441. sublinear_config.num_worker = self._sublinear_memory_config.num_worker
  442. # profile
  443. if self._profiling:
  444. self._profiler = GraphProfiler(graph)
  445. if int(os.getenv("MEGENGINE_INPLACE_UPDATE", "0")):
  446. graph.options.var_sanity_check_first_run = False
  447. def _compile(self):
  448. graph = self._graph = G.Graph()
  449. graph.options.async_exec_level = 0b100
  450. self._apply_graph_options(graph)
  451. # graph.options.graph_opt_level = 0
  452. need_reset_nodes = self._need_reset_nodes = []
  453. # links enforce ordering of I/O nodes
  454. in_out_links = ()
  455. io_links = ()
  456. readers = []
  457. if self._capture_as_const:
  458. for h in itertools.chain(self._arg_bindings, self._kwarg_bindings.values()):
  459. info = self._tinfo[h]
  460. opnode = info.data_setter = G.InputNode(
  461. device=info.device,
  462. dtype=info.dtype,
  463. shape=info.shape or (1,),
  464. graph=graph,
  465. use_static_shape=_input_node_use_static_shape(),
  466. )
  467. need_reset_nodes.append(opnode)
  468. info.varnode = opnode.outputs[0]
  469. in_out_links += opnode.outputs[1:]
  470. cnt_data, cnt_value, cnt_shape = 0, 0, 0
  471. for op, ihandles, ohandles in self._seq:
  472. if isinstance(op, str) and op == "Const":
  473. assert len(ihandles) == 0
  474. (h,) = ohandles
  475. info = self._tinfo[h]
  476. if not hasattr(info, "varnode"):
  477. assert info.external
  478. assert info.bound_data
  479. info.varnode = graph.make_const(
  480. info.bound_data.numpy(),
  481. info.bound_data.dtype,
  482. info.bound_data.device,
  483. )
  484. continue
  485. require_links = type(op) in _io_op_types
  486. ivars = []
  487. for i, h in enumerate(ihandles):
  488. info = self._tinfo[h]
  489. if not hasattr(info, "varnode"):
  490. assert info.external
  491. if info.bound_data:
  492. if hasattr(info, "is_const") and info.is_const:
  493. info.varnode = graph.make_const(
  494. info.bound_data.numpy(),
  495. info.bound_data.dtype,
  496. info.bound_data.device,
  497. )
  498. else:
  499. info.varnode = graph.make_const(
  500. info.bound_data._dev_tensor()
  501. # info.bound_data.numpy()
  502. )
  503. else:
  504. opnode = info.data_setter = G.InputNode(
  505. *in_out_links,
  506. device=info.device,
  507. dtype=info.dtype,
  508. shape=info.shape or (1,),
  509. graph=graph,
  510. use_static_shape=_input_node_use_static_shape(),
  511. )
  512. need_reset_nodes.append(opnode)
  513. info.varnode, *in_out_links = opnode.outputs
  514. if require_links and i == 0 and len(io_links) > 0:
  515. opnode = G.VirtualDepNode(
  516. [info.varnode, *io_links], str(io_links[0].device)
  517. )
  518. info.varnode = opnode.outputs[0]
  519. io_links = (info.varnode,)
  520. ivars.append(info.varnode)
  521. if isinstance(op, BackwardGraph):
  522. ovars = G.apply_backward_varnode(op, *ivars)
  523. else:
  524. ovars = G.apply_normal_varnode(op, *ivars)
  525. if require_links and len(ovars) > 0:
  526. io_links = (ovars[0],)
  527. assert len(ovars) == len(ohandles)
  528. for h, v in zip(ohandles, ovars):
  529. info = self._tinfo[h]
  530. info.varnode = v
  531. def add_reader(opnode):
  532. nonlocal in_out_links
  533. need_reset_nodes.append(opnode)
  534. readers.append(opnode.outputs[0])
  535. in_out_links = opnode.outputs
  536. if info.data_read:
  537. # Shape can be obtained from data so doesn't need its own
  538. # output node. On the other hand, value is read separately
  539. # to leverage eager h2d copy
  540. cnt_data += 1
  541. info.shape_read = False
  542. opnode = info.data_reader = G.OutputNode(v, *in_out_links)
  543. add_reader(opnode)
  544. if info.value_read:
  545. cnt_value += 1
  546. opnode = info.value_reader = G.ValueOutputNode(v, *in_out_links)
  547. add_reader(opnode)
  548. if info.shape_read:
  549. cnt_shape += 1
  550. opnode = info.shape_reader = G.AttrOutputNode(v, *in_out_links)
  551. add_reader(opnode)
  552. # FIXME
  553. if self._graph_opt_level is not None:
  554. graph.options.graph_opt_level = self._graph_opt_level
  555. else:
  556. graph.options.graph_opt_level = 2
  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. if is_tracing():
  564. return self.__wrapped__(*args, **kwargs)
  565. with self._setup():
  566. if self._capture_as_const:
  567. self._process_inputs(*args, **kwargs)
  568. outputs = self.__wrapped__(*args, **kwargs)
  569. transform = False
  570. if outputs is not None:
  571. if not isinstance(outputs, collections.abc.Sequence):
  572. transform = True
  573. outputs = (outputs,)
  574. for o in outputs:
  575. if o._copied:
  576. self._active_tensors[o.mixin_handle] = TensorWeakRef(o)
  577. if self._untraced and self._symbolic:
  578. self._lazy_eval_tensors[o.mixin_handle] = TensorWeakRef(o)
  579. if self._capture_as_const:
  580. self._process_outputs(outputs)
  581. if transform:
  582. outputs = outputs[0]
  583. return outputs
  584. def dump(
  585. self,
  586. file,
  587. *,
  588. arg_names=None,
  589. output_names=None,
  590. append=False,
  591. optimize_for_inference=True,
  592. **kwargs
  593. ):
  594. r"""
  595. Serializes trace to file system.
  596. :param file: output file, could be file object or filename.
  597. :param arg_names: names of the input tensors in the traced function.
  598. :param output_names: names of the output tensors in the traced function,
  599. use the default name if not specified.
  600. :param append: whether output is appended to ``file``.
  601. Only works when ``file`` is str.
  602. :param optimize_for_inference: enbale optmizations,
  603. will skip all optimize options if this is False. Default: True
  604. :Keyword Arguments:
  605. * enable_io16xc32 --
  606. whether to use float16 for I/O between oprs and use
  607. float32 as internal computation precision. Note the output var would be
  608. changed to float16.
  609. * enable_ioc16 --
  610. whether to use float16 for both I/O and computation
  611. precision.
  612. * enable_hwcd4 --
  613. whether to use NHWCD4 data layout. This is faster on some
  614. OpenCL backend.
  615. * enable_nchw88 --
  616. whether to use NCHW88 data layout, currently
  617. used in X86 AVX backend.
  618. * enable_nchw44 --
  619. whether to use NCHW44 data layout, currently
  620. used in arm backend.
  621. * enable_nchw44_dot --
  622. whether to use NCHW44_dot data layout, currently
  623. used in armv8.2+dotprod backend.
  624. * enable_nchw4 --
  625. whether to use NCHW4 data layout, currently
  626. used in nvidia backend(based on cudnn).
  627. * enable_nchw32 --
  628. whether to use NCHW32 data layout, currently
  629. used in nvidia backend with tensorcore(based on cudnn).
  630. * enable_chwn4 --
  631. whether to use CHWN4 data layout, currently
  632. used in nvidia backend with tensorcore.
  633. * enable_fuse_conv_bias_nonlinearity: whether to fuse conv+bias+nonlinearty
  634. into one opr.
  635. * enable_fuse_conv_bias_with_z: whether to fuse conv_bias with z
  636. input for inference on nvidia backend(this optimization pass will
  637. result in mismatch of the precision of output of training and
  638. inference)
  639. """
  640. if not self._capture_as_const:
  641. raise ValueError(
  642. "you must specify capture_as_const=True at __init__ to use dump"
  643. )
  644. if self._untraced:
  645. raise RuntimeError("should run at least once before calling dump")
  646. if self._output_names and output_names:
  647. raise TypeError(
  648. "cannot specify output_names when output is already in dict format"
  649. )
  650. if output_names and not isinstance(output_names, collections.abc.Sequence):
  651. output_names = (output_names,)
  652. if output_names and len(output_names) != len(self._output_bindings):
  653. raise ValueError(
  654. "wrong number of output_names, should be {} values".format(
  655. len(self._output_bindings)
  656. )
  657. )
  658. if arg_names is None:
  659. arg_names = ["arg_%d" % i for i in range(len(self._arg_bindings))]
  660. if arg_names and not isinstance(arg_names, collections.abc.Sequence):
  661. arg_names = (arg_names,)
  662. if arg_names and len(arg_names) != len(self._arg_bindings):
  663. raise ValueError(
  664. "wrong number of arg_names, should be {} values".format(
  665. len(self._arg_bindings)
  666. )
  667. )
  668. output_names = output_names or self._output_names
  669. dumped_device = as_device("xpux")
  670. h2v = {}
  671. graph = G.Graph()
  672. # only graph_opt_level takes effect in dump
  673. self._apply_graph_options(graph)
  674. for i, h in enumerate(self._arg_bindings):
  675. info = self._tinfo[h]
  676. h2v[h] = graph.make_h2d(
  677. dtype=info.dtype,
  678. device=dumped_device,
  679. shape=info.shape or (1,),
  680. name=arg_names[i] if arg_names else None,
  681. )
  682. for k, h in self._kwarg_bindings.items():
  683. info = self._tinfo[h]
  684. h2v[h] = graph.make_h2d(
  685. dtype=info.dtype, device=dumped_device, shape=info.shape or (1,), name=k
  686. )
  687. for op, ihandles, ohandles in self._seq:
  688. if isinstance(op, str) and op == "Const":
  689. assert len(ihandles) == 0
  690. (h,) = ohandles
  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=info.device,
  697. )
  698. continue
  699. ivars = []
  700. for h in ihandles:
  701. info = self._tinfo[h]
  702. if h not in h2v:
  703. assert info.external
  704. assert info.bound_data
  705. h2v[h] = graph.make_const(
  706. info.bound_data.numpy(), dtype=info.dtype, device=dumped_device
  707. )
  708. ivars.append(h2v[h])
  709. ovars = G.apply_normal_varnode(op, *ivars)
  710. assert len(ovars) == len(ohandles)
  711. h2v.update(zip(ohandles, ovars))
  712. dest_vars = []
  713. for i, h in enumerate(self._output_bindings):
  714. v = h2v[h]
  715. if output_names:
  716. v.name = output_names[i]
  717. dest_vars.append(v)
  718. if optimize_for_inference:
  719. dest_vars = G.optimize_for_inference(dest_vars, **kwargs)
  720. if isinstance(file, str):
  721. permission = "wb" if append == False else "ab"
  722. file = open(file, permission)
  723. dump_content, dump_info = G.dump_graph(dest_vars)
  724. file.write(dump_content)
  725. return dump_info
  726. def _process_inputs(self, *args, **kwargs):
  727. if self._untraced:
  728. self._inputs_to_restore = []
  729. def record_input(x):
  730. if x is None:
  731. return
  732. h, info = self._new_handle()
  733. info.external = False
  734. info.device = x.device
  735. info.dtype = x.dtype
  736. info.shape = x.numpy().shape
  737. x.mixin_handle = h
  738. x.recording = True
  739. x._trace_mixin_info = info
  740. self._inputs_to_restore.append(x)
  741. return h
  742. self._arg_bindings = []
  743. for i, x in enumerate(args):
  744. if not isinstance(x, RawTensor):
  745. raise TypeError(
  746. "positional arguments should all be tensor "
  747. "but args[%d] cannot be recognized as one" % i
  748. )
  749. self._arg_bindings.append(record_input(x))
  750. self._kwarg_bindings = {}
  751. for k, x in kwargs.items():
  752. if isinstance(x, RawTensor):
  753. self._kwarg_bindings[k] = record_input(x)
  754. else:
  755. if len(args) != len(self._arg_bindings):
  756. raise TraceMismatchError("positional argument length mismatch")
  757. self._tensor_remaps = {}
  758. for i, (h, x) in enumerate(zip(self._arg_bindings, args)):
  759. if not isinstance(x, RawTensor):
  760. raise TypeError(
  761. "positional arguments should all be tensor "
  762. "but args[%d] cannot be recognized as one" % i
  763. )
  764. info = self._tinfo[h]
  765. if x.dtype != info.dtype:
  766. raise TypeError("args[%d].dtype different from last time" % i)
  767. if x.device != info.device:
  768. raise TypeError("args[%d].device different from last time" % i)
  769. info.data_setter.set_value(x._dev_tensor())
  770. self._tensor_remaps[x._handle] = CompiledTensorProxy(h)
  771. kwargs_tensors = {}
  772. for k, x in kwargs.items():
  773. if isinstance(x, RawTensor):
  774. kwargs_tensors[k] = x
  775. if set(kwargs_tensors) != set(self._kwarg_bindings):
  776. too_many = set(kwargs_tensors) - set(self._kwarg_bindings)
  777. too_few = set(self._kwarg_bindings) - set(kwargs_tensors)
  778. if too_many:
  779. raise TraceMismatchError(
  780. "keyword arguments found to be tensor this time "
  781. "but were non-tensor previously: %s" % " ".join(too_many)
  782. )
  783. if too_few:
  784. raise TraceMismatchError(
  785. "keyword arguments found to be non-tensor this time "
  786. "but were tensor previously: %s" % " ".join(too_few)
  787. )
  788. for k, h in self._kwarg_bindings.items():
  789. x = kwargs_tensors[k]
  790. info = self._tinfo[h]
  791. if x.dtype != info.dtype:
  792. raise TypeError("kwargs[%s].dtype different from last time" % k)
  793. if x.device != info.device:
  794. raise TypeError("kwargs[%s].device different from last time" % k)
  795. info.data_setter.set_value(x._dev_tensor())
  796. self._tensor_remaps[x._handle] = CompiledTensorProxy(h)
  797. def _process_outputs(self, outputs):
  798. output_names = None
  799. if isinstance(outputs, collections.abc.Mapping):
  800. output_names, outputs = zip(*sorted(outputs.items()))
  801. elif not isinstance(outputs, collections.abc.Sequence):
  802. outputs = (outputs,)
  803. if not self._untraced:
  804. if output_names != self._output_names:
  805. too_many = set(output_names) - set(self._output_names)
  806. too_few = set(self._output_names) - set(output_names)
  807. if too_many:
  808. raise TraceMismatchError(
  809. "output has more keys than last time: %s" % " ".join(too_many)
  810. )
  811. if too_few:
  812. raise TraceMismatchError(
  813. "output has less keys than last time: %s" % " ".join(too_few)
  814. )
  815. if len(outputs) != len(self._output_bindings):
  816. raise TraceMismatchError("output size differs from last time")
  817. else:
  818. self._output_names = output_names
  819. self._output_bindings = []
  820. for i, x in enumerate(outputs):
  821. if not isinstance(x, RawTensor):
  822. raise TypeError("every item of return value should be tensor")
  823. if self._untraced:
  824. h = x.mixin_handle
  825. if h < 0:
  826. raise RuntimeError("output is not computed from inputs")
  827. self._output_bindings.append(h)
  828. else:
  829. h = x.mixin_handle
  830. if h not in self._output_handles:
  831. raise RuntimeError("output is not computed from inputs")
  832. if h != self._output_bindings[i]:
  833. raise TraceMismatchError(
  834. "retval[%s] is a different tensor than last time"
  835. % (output_names and output_names[i] or i)
  836. )
  837. def get_profile(self):
  838. """
  839. Get profiling result for compiled trace.
  840. :return: a json compatible object.
  841. """
  842. if not self._profiler:
  843. raise RuntimeError("trace is not set with profiling=True")
  844. return json.loads(self._profiler.get())
  845. def trace(self, *args, **kwargs):
  846. raise NotImplementedError(
  847. "trace is deemed unbeneficial with the new "
  848. "tracing mechanism. You should alwasy use __call__."
  849. )
  850. class CompiledTensorProxy:
  851. """
  852. Duck-typed RawTensor
  853. """
  854. def __init__(self, handle):
  855. self.__handle = handle
  856. self._isscalar = False
  857. self.__info = active_trace._tinfo[handle]
  858. self.__shape = None
  859. self.__data = None
  860. self.__value = None
  861. @property
  862. def dtype(self):
  863. return self.__info.varnode.dtype
  864. @property
  865. def device(self):
  866. return self.__info.varnode.device
  867. @property
  868. def shape(self):
  869. if self._isscalar:
  870. return ()
  871. if self.__shape is None:
  872. if self.__info.shape_read:
  873. self.__shape = self.__info.shape_reader.get_value().shape
  874. elif self.__info.data_read:
  875. self.__shape = self._dev_tensor().shape
  876. else:
  877. # c++ will throw TraceReadError
  878. return None
  879. return self.__shape
  880. def numpy(self):
  881. if self.__value is None:
  882. if self.__info.value_read:
  883. self.__value = self.__info.value_reader.get_value()
  884. elif self.__info.data_read:
  885. self.__value = self._dev_tensor().numpy()
  886. else:
  887. # c++ will throw TraceReadError
  888. return None
  889. if self._isscalar:
  890. self.__value = self.__value.squeeze()
  891. return self.__value
  892. def _dev_tensor(self):
  893. if self.__data is None:
  894. if not self.__info.data_read:
  895. # c++ will throw TraceReadError
  896. return None
  897. self.__data = self.__info.data_reader.get_value()
  898. return self.__data
  899. def __del__(self):
  900. if self.__info.shape_read and self.__shape is not None:
  901. self.__info.shape_reader.drop_value()
  902. if self.__info.value_read and self.__value is not None:
  903. self.__info.value_reader.drop_value()
  904. if self.__info.data_read and self.__data is not None:
  905. self.__info.data_reader.drop_value()
  906. def assign_raw_tensor(lhs, rhs):
  907. lhs.__init__(rhs)
  908. def apply_symbolic_mode(op: OpDef, *args: RawTensor):
  909. graph = active_trace._lazy_eval_graph
  910. ivars = []
  911. for x in args:
  912. var = getattr(x, "_varnode", None)
  913. if var:
  914. ivars.append(var)
  915. else:
  916. data_setter = G.InputNode(
  917. device=x.device,
  918. dtype=x.dtype,
  919. shape=x.numpy().shape or (1,),
  920. graph=graph,
  921. use_static_shape=True,
  922. )
  923. var = data_setter.outputs[0]
  924. ivars.append(var)
  925. data_setter.set_value(x._dev_tensor())
  926. require_links = type(op) in _io_op_types
  927. if require_links and active_trace._lazy_eval_links:
  928. assert len(ivars) > 0, "op should has at least one input"
  929. opnode = G.VirtualDepNode(
  930. [ivars[0], *active_trace._lazy_eval_links],
  931. str(active_trace._lazy_eval_links[0].device),
  932. )
  933. ivars[0] = opnode.outputs[0]
  934. active_trace._lazy_eval_links = (ivars[0],)
  935. if isinstance(op, BackwardGraph):
  936. ovars = G.apply_backward_varnode(op, *ivars)
  937. else:
  938. ovars = G.apply_normal_varnode(op, *ivars)
  939. outputs = [RawTensor(o) for o in ovars]
  940. if require_links:
  941. active_trace._lazy_eval_links = (G.VarNode(outputs[0]._varnode),)
  942. return outputs
  943. def apply_const_symbolic_mode(value, dtype, device):
  944. graph = active_trace._lazy_eval_graph
  945. # don't need to unset tracing
  946. # because varnode construction will ignore tracing flag
  947. ret = RawTensor(graph.make_const(value, dtype=dtype, device=device))
  948. if np.array(value).ndim == 0:
  949. setscalar(ret)
  950. return (ret,)
  951. def apply_compiled_mode(op: OpDef, *args: RawTensor):
  952. if skip_tracing:
  953. args = [
  954. RawTensor(x._dev_tensor()) if x.__class__ is CompiledTensorProxy else x
  955. for x in args
  956. ]
  957. unset_tracing()
  958. ret = apply(op, *args)
  959. set_tracing()
  960. return ret
  961. return active_trace._apply_op(op, args)
  962. def apply_const_compiled_mode(value, dtype, device, is_const, no_cache):
  963. if skip_tracing:
  964. args = [
  965. RawTensor(x._dev_tensor()) if x.__class__ is CompiledTensorProxy else x
  966. for x in args
  967. ]
  968. unset_tracing()
  969. ret = RawTensor(value, dtype, device, False)
  970. set_tracing()
  971. return ret
  972. return active_trace._apply_const(value, dtype, device)
  973. def apply_with_tracing(op: OpDef, *args: RawTensor):
  974. if active_trace._symbolic:
  975. outputs = apply_symbolic_mode(op, *args)
  976. else:
  977. unset_tracing()
  978. outputs = apply(op, *args)
  979. set_tracing()
  980. active_trace._record_op(op, args, outputs)
  981. return list(outputs)
  982. def apply_const_with_tracing(value, dtype, device, is_const, no_cache):
  983. if active_trace._symbolic:
  984. outputs = apply_const_symbolic_mode(value, dtype, device)
  985. else:
  986. unset_tracing()
  987. outputs = (RawTensor(value, dtype, device, False),)
  988. set_tracing()
  989. active_trace._record_const(outputs)
  990. return list(outputs)

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