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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  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. graph.options.async_exec_level = 0b100
  332. self._apply_graph_options(graph)
  333. # graph.options.graph_opt_level = 0
  334. need_reset_nodes = self._need_reset_nodes = []
  335. # links enforce ordering of I/O nodes
  336. links = ()
  337. readers = []
  338. if self._capture_as_const:
  339. for h in itertools.chain(self._arg_bindings, self._kwarg_bindings.values()):
  340. info = self._tinfo[h]
  341. opnode = info.data_setter = G.InputNode(
  342. device=info.device, dtype=info.dtype, shape=info.shape, graph=graph
  343. )
  344. need_reset_nodes.append(opnode)
  345. info.varnode = opnode.outputs[0]
  346. links += opnode.outputs[1:]
  347. for op, ihandles, ohandles in self._seq:
  348. ivars = []
  349. for h in ihandles:
  350. info = self._tinfo[h]
  351. if not hasattr(info, "varnode"):
  352. assert info.external
  353. if info.bound_data:
  354. info.varnode = graph.make_const(info.bound_data._dev_tensor())
  355. else:
  356. opnode = info.data_setter = G.InputNode(
  357. *links,
  358. device=info.device,
  359. dtype=info.dtype,
  360. shape=info.shape,
  361. graph=graph,
  362. )
  363. need_reset_nodes.append(opnode)
  364. info.varnode, *links = opnode.outputs
  365. ivars.append(info.varnode)
  366. ovars = apply(op, *ivars)
  367. assert len(ovars) == len(ohandles)
  368. for h, v in zip(ohandles, ovars):
  369. info = self._tinfo[h]
  370. info.varnode = v
  371. def add_reader(opnode):
  372. nonlocal links
  373. need_reset_nodes.append(opnode)
  374. readers.append(opnode.outputs[0])
  375. links = opnode.outputs
  376. if info.data_read:
  377. # Shape can be obtained from data so doesn't need its own
  378. # output node. On the other hand, value is read separately
  379. # to leverage eager h2d copy
  380. info.shape_read = False
  381. opnode = info.data_reader = G.OutputNode(v, *links)
  382. add_reader(opnode)
  383. if info.value_read:
  384. opnode = info.value_reader = G.ValueOutputNode(v, *links)
  385. add_reader(opnode)
  386. if info.shape_read:
  387. opnode = info.shape_reader = G.AttrOutputNode(v, *links)
  388. add_reader(opnode)
  389. graph.compile(*readers)
  390. def _reset_exec_env(self):
  391. for opnode in self._need_reset_nodes:
  392. opnode.reset()
  393. def _require_shape(self, handle):
  394. info = self._tinfo[handle]
  395. info.shape_read = True
  396. def _require_value(self, handle):
  397. info = self._tinfo[handle]
  398. info.value_read = True
  399. def _require_data(self, handle):
  400. info = self._tinfo[handle]
  401. info.data_read = True
  402. def __call__(self, *args, **kwargs):
  403. with self._setup():
  404. if self._capture_as_const:
  405. self._process_inputs(*args, **kwargs)
  406. outputs = self.__wrapped__(*args, **kwargs)
  407. if self._capture_as_const:
  408. self._process_outputs(outputs)
  409. return outputs
  410. def dump(
  411. self,
  412. file,
  413. *,
  414. arg_names=None,
  415. output_names=None,
  416. append=False,
  417. optimize_for_inference=True,
  418. **kwargs
  419. ):
  420. r"""Serializes trace to file system.
  421. :param file: output file, could be file object or filename.
  422. :param arg_names: names of the input tensors in the traced function.
  423. :param output_names: names of the output tensors in the traced function,
  424. use the default name if not specified.
  425. :param append: whether output is appended to ``file``.
  426. Only works when ``file`` is str.
  427. :param optimize_for_inference: enbale optmizations,
  428. will skip all optimize options if this is False. Default: True
  429. :Keyword Arguments:
  430. * enable_io16xc32 --
  431. whether to use float16 for I/O between oprs and use
  432. float32 as internal computation precision. Note the output var would be
  433. changed to float16.
  434. * enable_ioc16 --
  435. whether to use float16 for both I/O and computation
  436. precision.
  437. * enable_hwcd4 --
  438. whether to use NHWCD4 data layout. This is faster on some
  439. OpenCL backend.
  440. * enable_nchw88 --
  441. whether to use NCHW88 data layout, currently
  442. used in X86 AVX backend.
  443. * enable_nchw44 --
  444. whether to use NCHW44 data layout, currently
  445. used in arm backend.
  446. * enable_nchw44_dot --
  447. whether to use NCHW44_dot data layout, currently
  448. used in armv8.2+dotprod backend.
  449. * enable_nchw4 --
  450. whether to use NCHW4 data layout, currently
  451. used in nvidia backend(based on cudnn).
  452. * enable_nchw32 --
  453. whether to use NCHW32 data layout, currently
  454. used in nvidia backend with tensorcore(based on cudnn).
  455. * enable_chwn4 --
  456. whether to use CHWN4 data layout, currently
  457. used in nvidia backend with tensorcore.
  458. * enable_fuse_conv_bias_nonlinearity: whether to fuse conv+bias+nonlinearty
  459. into one opr.
  460. * enable_fuse_conv_bias_with_z: whether to fuse conv_bias with z
  461. input for inference on nvidia backend(this optimization pass will
  462. result in mismatch of the precision of output of training and
  463. inference)
  464. """
  465. if not self._capture_as_const:
  466. raise ValueError(
  467. "you must specify capture_as_const=True at __init__ to use dump"
  468. )
  469. if self._untraced:
  470. raise RuntimeError("should run at least once before calling dump")
  471. if self._output_names and output_names:
  472. raise TypeError(
  473. "cannot specify output_names when output is already in dict format"
  474. )
  475. if output_names and not isinstance(output_names, collections.abc.Sequence):
  476. output_names = (output_names,)
  477. if output_names and len(output_names) != len(self._output_bindings):
  478. raise ValueError(
  479. "wrong number of output_names, should be {} values".format(
  480. len(self._output_bindings)
  481. )
  482. )
  483. if arg_names and not isinstance(arg_names, collections.abc.Sequence):
  484. arg_names = (arg_names,)
  485. if arg_names and len(arg_names) != len(self._arg_bindings):
  486. raise ValueError(
  487. "wrong number of arg_names, should be {} values".format(
  488. len(self._arg_bindings)
  489. )
  490. )
  491. output_names = output_names or self._output_names
  492. h2v = {}
  493. graph = G.Graph()
  494. for i, h in enumerate(self._arg_bindings):
  495. info = self._tinfo[h]
  496. h2v[h] = graph.make_h2d(
  497. dtype=info.dtype,
  498. device=info.device,
  499. shape=info.shape,
  500. name=arg_names[i] if arg_names else None,
  501. )
  502. for k, h in self._kwarg_bindings.items():
  503. info = self._tinfo[h]
  504. h2v[h] = graph.make_h2d(
  505. dtype=info.dtype, device=info.device, shape=info.shape, name=k
  506. )
  507. for op, ihandles, ohandles in self._seq:
  508. ivars = []
  509. for h in ihandles:
  510. info = self._tinfo[h]
  511. if h not in h2v:
  512. assert info.external
  513. assert info.bound_data
  514. h2v[h] = graph.make_const(
  515. info.bound_data.numpy(), dtype=info.dtype, device=info.device
  516. )
  517. ivars.append(h2v[h])
  518. ovars = apply(op, *ivars)
  519. assert len(ovars) == len(ohandles)
  520. h2v.update(zip(ohandles, ovars))
  521. dest_vars = []
  522. for i, h in enumerate(self._output_bindings):
  523. v = h2v[h]
  524. if output_names:
  525. v.name = output_names[i]
  526. dest_vars.append(v)
  527. if optimize_for_inference:
  528. dest_vars = G.optimize_for_inference(dest_vars, **kwargs)
  529. if isinstance(file, str):
  530. permission = "wb" if append == False else "ab"
  531. file = open(file, permission)
  532. dump_content, dump_info = G.dump_graph(dest_vars)
  533. file.write(dump_content)
  534. return dump_info
  535. def _process_inputs(self, *args, **kwargs):
  536. if self._untraced:
  537. self._inputs_to_restore = []
  538. def record_input(x):
  539. if x is None:
  540. return
  541. h, info = self._new_handle()
  542. info.external = False
  543. info.device = x.device
  544. info.dtype = x.dtype
  545. info.shape = x.shape
  546. TraceMixin._TraceMixin__inject(x, h)
  547. self._inputs_to_restore.append(x)
  548. return h
  549. self._arg_bindings = []
  550. for i, x in enumerate(args):
  551. x = find_raw_tensor(x)
  552. if x is None:
  553. raise TypeError(
  554. "positional arguments should all be tensor "
  555. "but args[%d] cannot be recognized as one" % i
  556. )
  557. self._arg_bindings.append(record_input(x))
  558. self._kwarg_bindings = {}
  559. for k, x in kwargs.items():
  560. x = find_raw_tensor(x)
  561. if x is not None:
  562. self._kwarg_bindings[k] = record_input(x)
  563. else:
  564. if len(args) != len(self._arg_bindings):
  565. raise TraceMismatchError("positional argument length mismatch")
  566. self._tensor_remaps = {}
  567. for i, (h, x) in enumerate(zip(self._arg_bindings, args)):
  568. x = find_raw_tensor(x)
  569. if x is None:
  570. raise TypeError(
  571. "positional arguments should all be tensor "
  572. "but args[%d] cannot be recognized as one" % i
  573. )
  574. info = self._tinfo[h]
  575. if x.dtype != info.dtype:
  576. raise TypeError("args[%d].dtype different from last time" % i)
  577. if x.device != info.device:
  578. raise TypeError("args[%d].device different from last time" % i)
  579. info.data_setter.set_value(x._dev_tensor())
  580. self._tensor_remaps[x] = CompiledTensorProxy(h)
  581. kwargs_tensors = {}
  582. for k, x in kwargs.items():
  583. x = find_raw_tensor(x)
  584. if x is not None:
  585. kwargs_tensors[k] = x
  586. if set(kwargs_tensors) != set(self._kwarg_bindings):
  587. too_many = set(kwargs_tensors) - set(self._kwarg_bindings)
  588. too_few = set(self._kwarg_bindings) - set(kwargs_tensors)
  589. if too_many:
  590. raise TraceMismatchError(
  591. "keyword arguments found to be tensor this time "
  592. "but were non-tensor previously: %s" % " ".join(too_many)
  593. )
  594. if too_few:
  595. raise TraceMismatchError(
  596. "keyword arguments found to be non-tensor this time "
  597. "but were tensor previously: %s" % " ".join(too_few)
  598. )
  599. for k, h in self._kwarg_bindings.items():
  600. x = kwargs_tensors[k]
  601. info = self._tinfo[h]
  602. if x.dtype != info.dtype:
  603. raise TypeError("kwargs[%s].dtype different from last time" % k)
  604. if x.device != info.device:
  605. raise TypeError("kwargs[%s].device different from last time" % k)
  606. info.data_setter.set_value(x._dev_tensor())
  607. self._tensor_remaps[x] = CompiledTensorProxy(h)
  608. def _process_outputs(self, outputs):
  609. output_names = None
  610. if isinstance(outputs, collections.abc.Mapping):
  611. output_names, outputs = zip(*sorted(outputs.items()))
  612. elif not isinstance(outputs, collections.abc.Sequence):
  613. outputs = (outputs,)
  614. if not self._untraced:
  615. if output_names != self._output_names:
  616. too_many = set(output_names) - set(self._output_names)
  617. too_few = set(self._output_names) - set(output_names)
  618. if too_many:
  619. raise TraceMismatchError(
  620. "output has more keys than last time: %s" % " ".join(too_many)
  621. )
  622. if too_few:
  623. raise TraceMismatchError(
  624. "output has less keys than last time: %s" % " ".join(too_few)
  625. )
  626. if len(outputs) != len(self._output_bindings):
  627. raise TraceMismatchError("output size differs from last time")
  628. else:
  629. self._output_names = output_names
  630. self._output_bindings = []
  631. for i, x in enumerate(outputs):
  632. x = find_raw_tensor(x)
  633. if x is None:
  634. raise TypeError("every item of return value should be tensor")
  635. if self._untraced:
  636. if not isinstance(x, TraceMixin):
  637. raise RuntimeError("output is not computed from inputs")
  638. h = x._TraceMixin__handle
  639. self._output_bindings.append(h)
  640. else:
  641. if not isinstance(x, CompiledTensorProxy):
  642. raise RuntimeError("output is not computed from inputs")
  643. h = x._CompiledTensorProxy__handle
  644. if h != self._output_bindings[i]:
  645. raise TraceMismatchError(
  646. "retval[%s] is a different tensor than last time"
  647. % (output_names and output_names[i] or i)
  648. )
  649. def get_profile(self):
  650. """
  651. Get profiling result for compiled trace.
  652. :return: a json compatible object.
  653. """
  654. if not self._profiler:
  655. raise RuntimeError("trace is not set with profiling=True")
  656. return json.loads(self._profiler.get())
  657. def trace(self, *args, **kwargs):
  658. raise NotImplementedError(
  659. "trace is deemed unbeneficial with the new "
  660. "tracing mechanism. You should alwasy use __call__."
  661. )
  662. class CompiledTensorProxy(RawTensor):
  663. """
  664. Duck-typed RawTensor
  665. """
  666. def __init__(self, handle):
  667. self.__handle = handle
  668. self.__info = active_trace._tinfo[handle]
  669. self.__shape = None
  670. self.__data = None
  671. self.__value = None
  672. @property
  673. def dtype(self):
  674. return self.__info.varnode.dtype
  675. @property
  676. def device(self):
  677. return self.__info.varnode.device
  678. @property
  679. def shape(self):
  680. if self.__shape is None:
  681. if self.__info.shape_read:
  682. self.__shape = self.__info.shape_reader.get_value().shape
  683. elif self.__info.data_read:
  684. self.__shape = self._dev_tensor().shape
  685. else:
  686. raise TraceMismatchError("shape of this tensor is not read in trace")
  687. return self.__shape
  688. def numpy(self):
  689. if self.__value is None:
  690. if self.__info.value_read:
  691. self.__value = self.__info.value_reader.get_value()
  692. elif self.__info.data_read:
  693. self.__value = self._dev_tensor().numpy()
  694. else:
  695. raise TraceMismatchError("value of this tensor is not read in trace")
  696. return self.__value
  697. def _dev_tensor(self):
  698. if self.__data is None:
  699. if not self.__info.data_read:
  700. raise TraceMismatchError("raw data of this tensor is not read in trace")
  701. self.__data = self.__info.data_reader.get_value()
  702. return self.__data
  703. def __del__(self):
  704. if self.__info.shape_read and self.__shape is not None:
  705. self.__info.shape_reader.drop_value()
  706. if self.__info.value_read and self.__value is not None:
  707. self.__info.value_reader.drop_value()
  708. if self.__info.data_read and self.__data is not None:
  709. self.__info.data_reader.drop_value()
  710. class LazyEvalTensor(RawTensor):
  711. def __init__(self, varnode):
  712. self.__varnode = varnode
  713. @property
  714. def dtype(self):
  715. return self.__varnode.dtype
  716. @property
  717. def device(self):
  718. return self.__varnode.device
  719. @property
  720. def shape(self):
  721. return self.__varnode.shape
  722. def numpy(self):
  723. return self.__varnode.value
  724. def _dev_tensor(self):
  725. raise RuntimeError("cannot access data during symbolic tracing")
  726. class TraceMixin:
  727. __subclass_cache = {}
  728. def __inject(self, handle):
  729. cache = __class__.__subclass_cache
  730. cls = self.__class__
  731. subcls = cache.get(cls)
  732. if subcls is None:
  733. subcls = cache[cls] = type("Traced" + cls.__name__, (__class__, cls), {})
  734. self.__class__ = subcls
  735. self.__handle = handle
  736. self.__cls = cls
  737. return self
  738. def __restore(self):
  739. cls = self.__cls
  740. del self.__handle
  741. del self.__cls
  742. self.__class__ = cls
  743. return self
  744. @property
  745. def shape(self):
  746. if not skip_tracing:
  747. active_trace._require_shape(self.__handle)
  748. return super().shape
  749. def numpy(self):
  750. if not skip_tracing:
  751. active_trace._require_value(self.__handle)
  752. return super().numpy()
  753. def _dev_tensor(self):
  754. if not skip_tracing:
  755. active_trace._require_data(self.__handle)
  756. return super()._dev_tensor()
  757. class TracedRawTensor(TraceMixin, RawTensor):
  758. pass
  759. class TracedLazyTensor(TraceMixin, LazyEvalTensor):
  760. pass
  761. def assign_raw_tensor(lhs, rhs):
  762. handle = rhs._handle
  763. rhs.__dict__.clear()
  764. lhs.__dict__.clear()
  765. lhs.__class__ = RawTensor
  766. lhs.__init__(handle)
  767. # this hook turns RawTensor into LazyEvalTensor
  768. @apply.register()
  769. def apply_symbolic_mode(op: OpDef, *args: RawTensor):
  770. graph = active_trace._lazy_eval_graph
  771. ivars = [
  772. getattr(x, "_LazyEvalTensor__varnode", None)
  773. or graph.make_const(x._dev_tensor())
  774. for x in args
  775. ]
  776. ovars = apply(op, *ivars)
  777. outputs = [LazyEvalTensor(v) for v in ovars]
  778. active_trace._lazy_eval_tensors.extend(weakref.ref(oup) for oup in outputs)
  779. return outputs
  780. apply.disable(apply_symbolic_mode)
  781. @apply.register()
  782. def apply_const_symbolic_mode(op: Const, *args: RawTensor):
  783. graph = active_trace._lazy_eval_graph
  784. ret = LazyEvalTensor(graph.make_const(op.value, dtype=op.dtype, device=op.device))
  785. active_trace._lazy_eval_tensors.append(weakref.ref(ret))
  786. return (ret,)
  787. apply.disable(apply_const_symbolic_mode)
  788. @apply.register()
  789. def apply_compiled_mode(op: OpDef, *args: RawTensor):
  790. if skip_tracing:
  791. args = [
  792. as_raw_tensor(x._dev_tensor()) if x.__class__ is CompiledTensorProxy else x
  793. for x in args
  794. ]
  795. return apply.super(op, *args)
  796. return active_trace._apply_op(op, args)
  797. apply.disable(apply_compiled_mode)
  798. # this hook injects TraceMixin
  799. @apply.register()
  800. def apply_with_tracing(op: OpDef, *args: RawTensor):
  801. outputs = apply.super(op, *args)
  802. active_trace._record_op(op, args, outputs)
  803. return outputs
  804. apply.disable(apply_with_tracing)
  805. @apply.register()
  806. def apply_const_with_tracing(op: Const, *args: RawTensor):
  807. outputs = apply.super(op, *args)
  808. active_trace._record_const(op, outputs)
  809. return outputs
  810. apply.disable(apply_const_with_tracing)
  811. class BrokenRawTensor(RawTensor):
  812. def __getattribute__(self, _):
  813. raise RuntimeError("broken due to misuse of tracing")
  814. def __setattr__(self, *_):
  815. raise RuntimeError("broken due to misuse of tracing")
  816. @functools.singledispatch
  817. def find_raw_tensor(x):
  818. return None
  819. @find_raw_tensor.register(RawTensor)
  820. def _(x):
  821. return x
  822. @find_raw_tensor.register(TensorWrapperBase)
  823. def _(x):
  824. x = getattr(x, "__wrapped__", None)
  825. if x is not None:
  826. return find_raw_tensor(x)
  827. @find_raw_tensor.register(Tensor)
  828. def _(x):
  829. x = getattr(x, "_data", None)
  830. if x is not None:
  831. return find_raw_tensor(x)

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