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

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

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