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

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

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