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

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

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