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

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

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