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

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

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