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

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

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