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

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

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