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

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

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