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

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

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