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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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(info.bound_data._dev_tensor())
  514. ivars.append(h2v[h])
  515. ovars = apply(op, *ivars)
  516. assert len(ovars) == len(ohandles)
  517. h2v.update(zip(ohandles, ovars))
  518. dest_vars = []
  519. for i, h in enumerate(self._output_bindings):
  520. v = h2v[h]
  521. if output_names:
  522. v.name = output_names[i]
  523. dest_vars.append(v)
  524. if optimize_for_inference:
  525. dest_vars = G.optimize_for_inference(dest_vars, **kwargs)
  526. if isinstance(file, str):
  527. permission = "wb" if append == False else "ab"
  528. file = open(file, permission)
  529. dump_content, dump_info = G.dump_graph(dest_vars)
  530. file.write(dump_content)
  531. return dump_info
  532. def _process_inputs(self, *args, **kwargs):
  533. if self._untraced:
  534. self._inputs_to_restore = []
  535. def record_input(x):
  536. if x is None:
  537. return
  538. h, info = self._new_handle()
  539. info.external = False
  540. info.device = x.device
  541. info.dtype = x.dtype
  542. info.shape = x.shape
  543. TraceMixin._TraceMixin__inject(x, h)
  544. self._inputs_to_restore.append(x)
  545. return h
  546. self._arg_bindings = []
  547. for i, x in enumerate(args):
  548. x = find_raw_tensor(x)
  549. if x is None:
  550. raise TypeError(
  551. "positional arguments should all be tensor "
  552. "but args[%d] cannot be recognized as one" % i
  553. )
  554. self._arg_bindings.append(record_input(x))
  555. self._kwarg_bindings = {}
  556. for k, x in kwargs.items():
  557. x = find_raw_tensor(x)
  558. if x is not None:
  559. self._kwarg_bindings[k] = record_input(x)
  560. else:
  561. if len(args) != len(self._arg_bindings):
  562. raise TraceMismatchError("positional argument length mismatch")
  563. self._tensor_remaps = {}
  564. for i, (h, x) in enumerate(zip(self._arg_bindings, args)):
  565. x = find_raw_tensor(x)
  566. if x is None:
  567. raise TypeError(
  568. "positional arguments should all be tensor "
  569. "but args[%d] cannot be recognized as one" % i
  570. )
  571. info = self._tinfo[h]
  572. if x.dtype != info.dtype:
  573. raise TypeError("args[%d].dtype different from last time" % i)
  574. if x.device != info.device:
  575. raise TypeError("args[%d].device different from last time" % i)
  576. info.data_setter.set_value(x._dev_tensor())
  577. self._tensor_remaps[x] = CompiledTensorProxy(h)
  578. kwargs_tensors = {}
  579. for k, x in kwargs.items():
  580. x = find_raw_tensor(x)
  581. if x is not None:
  582. kwargs_tensors[k] = x
  583. if set(kwargs_tensors) != set(self._kwarg_bindings):
  584. too_many = set(kwargs_tensors) - set(self._kwarg_bindings)
  585. too_few = set(self._kwarg_bindings) - set(kwargs_tensors)
  586. if too_many:
  587. raise TraceMismatchError(
  588. "keyword arguments found to be tensor this time "
  589. "but were non-tensor previously: %s" % " ".join(too_many)
  590. )
  591. if too_few:
  592. raise TraceMismatchError(
  593. "keyword arguments found to be non-tensor this time "
  594. "but were tensor previously: %s" % " ".join(too_few)
  595. )
  596. for k, h in self._kwarg_bindings.items():
  597. x = kwargs_tensors[k]
  598. info = self._tinfo[h]
  599. if x.dtype != info.dtype:
  600. raise TypeError("kwargs[%s].dtype different from last time" % k)
  601. if x.device != info.device:
  602. raise TypeError("kwargs[%s].device different from last time" % k)
  603. info.data_setter.set_value(x._dev_tensor())
  604. self._tensor_remaps[x] = CompiledTensorProxy(h)
  605. def _process_outputs(self, outputs):
  606. output_names = None
  607. if isinstance(outputs, collections.abc.Mapping):
  608. output_names, outputs = zip(*sorted(outputs.items()))
  609. elif not isinstance(outputs, collections.abc.Sequence):
  610. outputs = (outputs,)
  611. if not self._untraced:
  612. if output_names != self._output_names:
  613. too_many = set(output_names) - set(self._output_names)
  614. too_few = set(self._output_names) - set(output_names)
  615. if too_many:
  616. raise TraceMismatchError(
  617. "output has more keys than last time: %s" % " ".join(too_many)
  618. )
  619. if too_few:
  620. raise TraceMismatchError(
  621. "output has less keys than last time: %s" % " ".join(too_few)
  622. )
  623. if len(outputs) != len(self._output_bindings):
  624. raise TraceMismatchError("output size differs from last time")
  625. else:
  626. self._output_names = output_names
  627. self._output_bindings = []
  628. for i, x in enumerate(outputs):
  629. x = find_raw_tensor(x)
  630. if x is None:
  631. raise TypeError("every item of return value should be tensor")
  632. if self._untraced:
  633. if not isinstance(x, TraceMixin):
  634. raise RuntimeError("output is not computed from inputs")
  635. h = x._TraceMixin__handle
  636. self._output_bindings.append(h)
  637. else:
  638. if not isinstance(x, CompiledTensorProxy):
  639. raise RuntimeError("output is not computed from inputs")
  640. h = x._CompiledTensorProxy__handle
  641. if h != self._output_bindings[i]:
  642. raise TraceMismatchError(
  643. "retval[%s] is a different tensor than last time"
  644. % (output_names and output_names[i] or i)
  645. )
  646. def get_profile(self):
  647. """
  648. Get profiling result for compiled trace.
  649. :return: a json compatible object.
  650. """
  651. if not self._profiler:
  652. raise RuntimeError("trace is not set with profiling=True")
  653. return json.loads(self._profiler.get())
  654. def trace(self, *args, **kwargs):
  655. raise NotImplementedError(
  656. "trace is deemed unbeneficial with the new "
  657. "tracing mechanism. You should alwasy use __call__."
  658. )
  659. class CompiledTensorProxy(RawTensor):
  660. """
  661. Duck-typed RawTensor
  662. """
  663. def __init__(self, handle):
  664. self.__handle = handle
  665. self.__info = active_trace._tinfo[handle]
  666. self.__shape = None
  667. self.__data = None
  668. self.__value = None
  669. @property
  670. def dtype(self):
  671. return self.__info.varnode.dtype
  672. @property
  673. def device(self):
  674. return self.__info.varnode.device
  675. @property
  676. def shape(self):
  677. if self.__shape is None:
  678. if self.__info.shape_read:
  679. self.__shape = self.__info.shape_reader.get_value().shape
  680. elif self.__info.data_read:
  681. self.__shape = self._dev_tensor().shape
  682. else:
  683. raise TraceMismatchError("shape of this tensor is not read in trace")
  684. return self.__shape
  685. def numpy(self):
  686. if self.__value is None:
  687. if self.__info.value_read:
  688. self.__value = self.__info.value_reader.get_value()
  689. elif self.__info.data_read:
  690. self.__value = self._dev_tensor().numpy()
  691. else:
  692. raise TraceMismatchError("value of this tensor is not read in trace")
  693. return self.__value
  694. def _dev_tensor(self):
  695. if self.__data is None:
  696. if not self.__info.data_read:
  697. raise TraceMismatchError("raw data of this tensor is not read in trace")
  698. self.__data = self.__info.data_reader.get_value()
  699. return self.__data
  700. def __del__(self):
  701. if self.__info.shape_read and self.__shape is not None:
  702. self.__info.shape_reader.drop_value()
  703. if self.__info.value_read and self.__value is not None:
  704. self.__info.value_reader.drop_value()
  705. if self.__info.data_read and self.__data is not None:
  706. self.__info.data_reader.drop_value()
  707. class LazyEvalTensor(RawTensor):
  708. def __init__(self, varnode):
  709. self.__varnode = varnode
  710. @property
  711. def dtype(self):
  712. return self.__varnode.dtype
  713. @property
  714. def device(self):
  715. return self.__varnode.device
  716. @property
  717. def shape(self):
  718. return self.__varnode.shape
  719. def numpy(self):
  720. return self.__varnode.value
  721. def _dev_tensor(self):
  722. raise RuntimeError("cannot access data during symbolic tracing")
  723. class TraceMixin:
  724. __subclass_cache = {}
  725. def __inject(self, handle):
  726. cache = __class__.__subclass_cache
  727. cls = self.__class__
  728. subcls = cache.get(cls)
  729. if subcls is None:
  730. subcls = cache[cls] = type("Traced" + cls.__name__, (__class__, cls), {})
  731. self.__class__ = subcls
  732. self.__handle = handle
  733. self.__cls = cls
  734. return self
  735. def __restore(self):
  736. cls = self.__cls
  737. del self.__handle
  738. del self.__cls
  739. self.__class__ = cls
  740. return self
  741. @property
  742. def shape(self):
  743. if not skip_tracing:
  744. active_trace._require_shape(self.__handle)
  745. return super().shape
  746. def numpy(self):
  747. if not skip_tracing:
  748. active_trace._require_value(self.__handle)
  749. return super().numpy()
  750. def _dev_tensor(self):
  751. if not skip_tracing:
  752. active_trace._require_data(self.__handle)
  753. return super()._dev_tensor()
  754. class TracedRawTensor(TraceMixin, RawTensor):
  755. pass
  756. class TracedLazyTensor(TraceMixin, LazyEvalTensor):
  757. pass
  758. def assign_raw_tensor(lhs, rhs):
  759. handle = rhs._handle
  760. rhs.__dict__.clear()
  761. lhs.__dict__.clear()
  762. lhs.__class__ = RawTensor
  763. lhs.__init__(handle)
  764. # this hook turns RawTensor into LazyEvalTensor
  765. @apply.register()
  766. def apply_symbolic_mode(op: OpDef, *args: RawTensor):
  767. graph = active_trace._lazy_eval_graph
  768. ivars = [
  769. getattr(x, "_LazyEvalTensor__varnode", None)
  770. or graph.make_const(x._dev_tensor())
  771. for x in args
  772. ]
  773. ovars = apply(op, *ivars)
  774. outputs = [LazyEvalTensor(v) for v in ovars]
  775. active_trace._lazy_eval_tensors.extend(weakref.ref(oup) for oup in outputs)
  776. return outputs
  777. apply.disable(apply_symbolic_mode)
  778. @apply.register()
  779. def apply_const_symbolic_mode(op: Const, *args: RawTensor):
  780. graph = active_trace._lazy_eval_graph
  781. ret = LazyEvalTensor(graph.make_const(op.value, dtype=op.dtype, device=op.device))
  782. active_trace._lazy_eval_tensors.append(weakref.ref(ret))
  783. return (ret,)
  784. apply.disable(apply_const_symbolic_mode)
  785. @apply.register()
  786. def apply_compiled_mode(op: OpDef, *args: RawTensor):
  787. if skip_tracing:
  788. args = [
  789. as_raw_tensor(x._dev_tensor()) if x.__class__ is CompiledTensorProxy else x
  790. for x in args
  791. ]
  792. return apply.super(op, *args)
  793. return active_trace._apply_op(op, args)
  794. apply.disable(apply_compiled_mode)
  795. # this hook injects TraceMixin
  796. @apply.register()
  797. def apply_with_tracing(op: OpDef, *args: RawTensor):
  798. outputs = apply.super(op, *args)
  799. active_trace._record_op(op, args, outputs)
  800. return outputs
  801. apply.disable(apply_with_tracing)
  802. @apply.register()
  803. def apply_const_with_tracing(op: Const, *args: RawTensor):
  804. outputs = apply.super(op, *args)
  805. active_trace._record_const(op, outputs)
  806. return outputs
  807. apply.disable(apply_const_with_tracing)
  808. class BrokenRawTensor(RawTensor):
  809. def __getattribute__(self, _):
  810. raise RuntimeError("broken due to misuse of tracing")
  811. def __setattr__(self, *_):
  812. raise RuntimeError("broken due to misuse of tracing")
  813. @functools.singledispatch
  814. def find_raw_tensor(x):
  815. return None
  816. @find_raw_tensor.register(RawTensor)
  817. def _(x):
  818. return x
  819. @find_raw_tensor.register(TensorWrapperBase)
  820. def _(x):
  821. x = getattr(x, "__wrapped__", None)
  822. if x is not None:
  823. return find_raw_tensor(x)
  824. @find_raw_tensor.register(Tensor)
  825. def _(x):
  826. x = getattr(x, "_data", None)
  827. if x is not None:
  828. return find_raw_tensor(x)

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