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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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, BatchNorm, 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. Default: 2
  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 = 2,
  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. lazy_eval_graph.options.graph_opt_level = self._graph_opt_level
  337. lazy_eval_graph._set_priority_to_id([*lazy_eval_links, *readers])
  338. lazy_eval_graph.compile(*lazy_eval_links, *readers)
  339. lazy_eval_graph()
  340. for r, x in zip(readers, lazy_eval_tensors):
  341. # get values from lazy_eval_graph and assign to lazy_eval tensor
  342. x()._handle = RawTensor(r.op.get_value())._handle
  343. x()._reset_varnode()
  344. @contextlib.contextmanager
  345. def _setup(self):
  346. interrupted = False
  347. def do_enter():
  348. set_tracing()
  349. self._save_symbolic_shape = set_symbolic_shape(self._symbolic_shape)
  350. self._set_active(True)
  351. if self._untraced:
  352. self._init_trace(self._symbolic)
  353. else:
  354. set_compiled()
  355. if self._graph is None:
  356. self._compile()
  357. self._graph.execute()
  358. def do_finalize():
  359. escaped_tensors = self._take_escaped_tensors()
  360. if self._untraced:
  361. for x in escaped_tensors:
  362. if x():
  363. info = self._tinfo[x()._mixin_handle]
  364. info.data_read = True
  365. x()._mixin_handle = -1
  366. x()._recording = False
  367. if self._inputs_to_restore:
  368. for x in self._inputs_to_restore:
  369. x._mixin_handle = -1
  370. x._recording = False
  371. if self._symbolic and (
  372. self._lazy_eval_tensors or self._lazy_eval_links
  373. ):
  374. # eval lazy eval tensors
  375. self._lazy_eval(
  376. self._lazy_eval_graph,
  377. self._lazy_eval_tensors,
  378. self._lazy_eval_links,
  379. )
  380. self._lazy_eval_graph = None
  381. self._lazy_eval_tensors = None
  382. self._lazy_eval_links = None
  383. self._untraced = False
  384. else:
  385. # compiled_tensor leaks
  386. if self._pc == len(self._seq):
  387. for x in escaped_tensors:
  388. try:
  389. assign_raw_tensor(x(), RawTensor(x()._dev_tensor()))
  390. except RuntimeError:
  391. # TraceMismatchError thrown in do_exit
  392. pass
  393. self._graph.wait()
  394. self._reset_exec_env()
  395. # reset status
  396. self._pc = 0
  397. self._tensor_remaps = None
  398. self._set_active(False)
  399. set_symbolic_shape(self._save_symbolic_shape)
  400. unset_compiled()
  401. unset_tracing()
  402. def do_exit():
  403. unset_tracing()
  404. if not self._untraced and self._pc != len(self._seq):
  405. raise TraceMismatchError("premature end")
  406. if not self._symbolic or not self._untraced:
  407. # reset output tensors
  408. for x in self._active_tensors.values():
  409. if x() is not None:
  410. x()._dev_tensor()
  411. x()._reset_varnode()
  412. x()._mixin_handle = -1
  413. x()._recording = False
  414. x()._trace_mixin_info = None
  415. try:
  416. do_enter()
  417. yield
  418. do_exit()
  419. except:
  420. interrupted = True
  421. raise
  422. finally:
  423. do_finalize()
  424. if interrupted:
  425. self._reset()
  426. def _begin_excluded_region(self):
  427. if self._capture_as_const:
  428. raise RuntimeError(
  429. "exclude_from_trace cannot be used with capture_as_const"
  430. )
  431. if self._untraced:
  432. # conditionally reading a compiled tensor in excluded region
  433. # is permitted, so we have to assume every tensor might be read
  434. for x in self._active_tensors.values():
  435. if x():
  436. info = self._tinfo[x()._mixin_handle]
  437. info.exported = True
  438. info.data_read = True
  439. else:
  440. for x in self._active_tensors.values():
  441. if x():
  442. x()._dev_tensor()
  443. def _apply_graph_options(self, graph):
  444. graph.options.no_force_inplace = True
  445. graph.options.seq_opt.enable_seq_comp_node_opt = False
  446. graph.options.graph_opt_level = self._graph_opt_level
  447. # sublinear
  448. if self._sublinear_memory_config is not None:
  449. graph.options.enable_sublinear_memory_opt = True
  450. sublinear_config = graph.options.sublinear_mem_config
  451. sublinear_config.lb_memory = self._sublinear_memory_config.lb_memory
  452. sublinear_config.genetic_nr_iter = (
  453. self._sublinear_memory_config.genetic_nr_iter
  454. )
  455. sublinear_config.genetic_pool_size = (
  456. self._sublinear_memory_config.genetic_pool_size
  457. )
  458. sublinear_config.thresh_nr_try = self._sublinear_memory_config.thresh_nr_try
  459. sublinear_config.num_worker = self._sublinear_memory_config.num_worker
  460. # profile
  461. if self._profiling:
  462. self._profiler = GraphProfiler(graph)
  463. if int(os.getenv("MEGENGINE_INPLACE_UPDATE", "0")):
  464. graph.options.var_sanity_check_first_run = False
  465. def _compile(self):
  466. graph = self._graph = G.Graph()
  467. graph.options.async_exec_level = 0b100
  468. self._apply_graph_options(graph)
  469. # graph.options.graph_opt_level = 0
  470. need_reset_nodes = self._need_reset_nodes = []
  471. # links enforce ordering of I/O nodes
  472. in_out_links = ()
  473. io_links = ()
  474. readers = []
  475. if self._capture_as_const:
  476. for h in itertools.chain(self._arg_bindings, self._kwarg_bindings.values()):
  477. info = self._tinfo[h]
  478. opnode = info.data_setter = G.InputNode(
  479. device=info.device,
  480. dtype=info.dtype,
  481. shape=info.shape or (1,),
  482. graph=graph,
  483. use_static_shape=_input_node_use_static_shape(),
  484. )
  485. need_reset_nodes.append(opnode)
  486. info.varnode = opnode.outputs[0]
  487. in_out_links += opnode.outputs[1:]
  488. for op, ihandles, ohandles in self._seq:
  489. if isinstance(op, str) and op == "Const":
  490. assert len(ihandles) == 0
  491. (h,) = ohandles
  492. info = self._tinfo[h]
  493. if not hasattr(info, "varnode"):
  494. assert info.external
  495. assert info.bound_data
  496. info.varnode = graph.make_const(
  497. info.bound_data.numpy(),
  498. info.bound_data.dtype,
  499. info.bound_data.device,
  500. )
  501. continue
  502. require_links = type(op) in _io_op_types
  503. ivars = []
  504. for i, h in enumerate(ihandles):
  505. info = self._tinfo[h]
  506. if not hasattr(info, "varnode"):
  507. assert info.external
  508. if info.bound_data:
  509. if hasattr(info, "is_const") and info.is_const:
  510. info.varnode = graph.make_const(
  511. info.bound_data.numpy(),
  512. info.bound_data.dtype,
  513. info.bound_data.device,
  514. )
  515. else:
  516. info.varnode = graph.make_const(
  517. info.bound_data._dev_tensor()
  518. # info.bound_data.numpy()
  519. )
  520. else:
  521. opnode = info.data_setter = G.InputNode(
  522. *in_out_links,
  523. device=info.device,
  524. dtype=info.dtype,
  525. shape=info.shape or (1,),
  526. graph=graph,
  527. use_static_shape=_input_node_use_static_shape(),
  528. )
  529. need_reset_nodes.append(opnode)
  530. info.varnode, *in_out_links = opnode.outputs
  531. if require_links and i == 0 and len(io_links) > 0:
  532. opnode = G.VirtualDepNode(
  533. [info.varnode, *io_links], str(io_links[0].device)
  534. )
  535. info.varnode = opnode.outputs[0]
  536. io_links = (info.varnode,)
  537. ivars.append(info.varnode)
  538. if isinstance(op, BackwardGraph):
  539. ovars = G.apply_backward_varnode(op, *ivars)
  540. else:
  541. ovars = G.apply_normal_varnode(op, *ivars)
  542. if require_links and len(ovars) > 0:
  543. io_links = (ovars[0],)
  544. assert len(ovars) == len(ohandles)
  545. for h, v in zip(ohandles, ovars):
  546. info = self._tinfo[h]
  547. info.varnode = v
  548. def add_reader(opnode):
  549. nonlocal in_out_links
  550. need_reset_nodes.append(opnode)
  551. readers.append(opnode.outputs[0])
  552. in_out_links = opnode.outputs
  553. if info.data_read:
  554. # Shape can be obtained from data so doesn't need its own
  555. # output node. On the other hand, value is read separately
  556. # to leverage eager h2d copy
  557. info.shape_read = False
  558. opnode = info.data_reader = G.OutputNode(v, *in_out_links)
  559. add_reader(opnode)
  560. if info.value_read:
  561. opnode = info.value_reader = G.ValueOutputNode(v, *in_out_links)
  562. add_reader(opnode)
  563. if info.shape_read:
  564. opnode = info.shape_reader = G.AttrOutputNode(v, *in_out_links)
  565. add_reader(opnode)
  566. graph.options.graph_opt_level = self._graph_opt_level
  567. graph._set_priority_to_id([*readers, *in_out_links, *io_links])
  568. graph.compile(*readers, *in_out_links, *io_links)
  569. def _reset_exec_env(self):
  570. for opnode in self._need_reset_nodes:
  571. opnode.reset()
  572. def __call__(self, *args, **kwargs):
  573. if is_tracing():
  574. return self.__wrapped__(*args, **kwargs)
  575. with self._setup():
  576. if self._capture_as_const:
  577. self._process_inputs(*args, **kwargs)
  578. outputs = self.__wrapped__(*args, **kwargs)
  579. if self._capture_as_const:
  580. self._process_outputs(outputs)
  581. # outputs could be None
  582. if outputs is not None:
  583. list_outputs = outputs
  584. if isinstance(outputs, collections.abc.Mapping):
  585. _, list_outputs = zip(*sorted(outputs.items()))
  586. elif not isinstance(outputs, collections.abc.Sequence):
  587. list_outputs = (outputs,)
  588. for o in list_outputs:
  589. # if outputs are copied, then use the newest info in trace data structure
  590. if o._copied:
  591. self._active_tensors[o._mixin_handle] = TensorWeakRef(o)
  592. if self._untraced and self._symbolic:
  593. self._lazy_eval_tensors[o._mixin_handle] = TensorWeakRef(o)
  594. return outputs
  595. def dump(
  596. self,
  597. file,
  598. *,
  599. arg_names=None,
  600. output_names=None,
  601. append=False,
  602. keep_var_name: int = 1,
  603. keep_opr_name: bool = False,
  604. keep_param_name: bool = False,
  605. keep_opr_priority: bool = False,
  606. strip_info_file=None,
  607. append_json=False,
  608. optimize_for_inference=True,
  609. **kwargs
  610. ):
  611. r"""
  612. Serializes trace to file system.
  613. :param file: output file, could be file object or filename.
  614. :param arg_names: names of the input tensors in the traced function.
  615. :param output_names: names of the output tensors in the traced function,
  616. use the default name if not specified.
  617. :param append: whether output is appended to ``file``.
  618. Only works when ``file`` is str.
  619. :param keep_var_name: level for keeping variable names:
  620. * 0: none of the names are kept
  621. * 1: (default)keep names of output vars
  622. * 2: keep names of all (output and internal) vars
  623. :param keep_opr_name: whether to keep operator names.
  624. :param keep_param_name: whether to keep param names, so param values can be
  625. easily manipulated after loading model
  626. :param keep_opr_priority: whether to keep priority setting for operators
  627. :param strip_info_file: a string for path or a file handler. if is not None,
  628. then the dump information for code strip would be written to ``strip_info_file``
  629. :param append_json: will be check when `strip_info_file` is not None. if set
  630. true, the information for code strip will be append to strip_info_file.
  631. if set false, will rewrite strip_info_file
  632. :param optimize_for_inference: enbale optmizations,
  633. will skip all optimize options if this is False. Default: True
  634. :Keyword Arguments:
  635. * enable_io16xc32 --
  636. whether to use float16 for I/O between oprs and use
  637. float32 as internal computation precision. Note the output var would be
  638. changed to float16.
  639. * enable_ioc16 --
  640. whether to use float16 for both I/O and computation
  641. precision.
  642. * enable_hwcd4 --
  643. whether to use NHWCD4 data layout. This is faster on some
  644. OpenCL backend.
  645. * enable_nchw88 --
  646. whether to use NCHW88 data layout, currently
  647. used in X86 AVX backend.
  648. * enable_nchw44 --
  649. whether to use NCHW44 data layout, currently
  650. used in arm backend.
  651. * enable_nchw44_dot --
  652. whether to use NCHW44_dot data layout, currently
  653. used in armv8.2+dotprod backend.
  654. * enable_nchw4 --
  655. whether to use NCHW4 data layout, currently
  656. used in nvidia backend(based on cudnn).
  657. * enable_nchw32 --
  658. whether to use NCHW32 data layout, currently
  659. used in nvidia backend with tensorcore(based on cudnn).
  660. * enable_chwn4 --
  661. whether to use CHWN4 data layout, currently
  662. used in nvidia backend with tensorcore.
  663. * enable_fuse_conv_bias_nonlinearity: whether to fuse conv+bias+nonlinearty
  664. into one opr.
  665. * enable_fuse_conv_bias_with_z: whether to fuse conv_bias with z
  666. input for inference on nvidia backend(this optimization pass will
  667. result in mismatch of the precision of output of training and
  668. inference)
  669. """
  670. if not self._capture_as_const:
  671. raise ValueError(
  672. "you must specify capture_as_const=True at __init__ to use dump"
  673. )
  674. if self._untraced:
  675. raise RuntimeError("should run at least once before calling dump")
  676. if self._output_names and output_names:
  677. raise TypeError(
  678. "cannot specify output_names when output is already in dict format"
  679. )
  680. if output_names and not isinstance(output_names, collections.abc.Sequence):
  681. output_names = (output_names,)
  682. if output_names and len(output_names) != len(self._output_bindings):
  683. raise ValueError(
  684. "wrong number of output_names, should be {} values".format(
  685. len(self._output_bindings)
  686. )
  687. )
  688. without_arg_names = arg_names is None
  689. if without_arg_names:
  690. arg_names = ["arg_%d" % i for i in range(len(self._arg_bindings))]
  691. if arg_names and not isinstance(arg_names, collections.abc.Sequence):
  692. arg_names = (arg_names,)
  693. if arg_names and len(arg_names) != len(self._arg_bindings):
  694. raise ValueError(
  695. "wrong number of arg_names, should be {} values".format(
  696. len(self._arg_bindings)
  697. )
  698. )
  699. output_names = output_names or self._output_names
  700. def dumped_device(info):
  701. device_name = info.device.logical_name
  702. if device_name[:3] in ("cpu", "gpu", "xpu"):
  703. return as_device("xpux")
  704. return info.device
  705. h2v = {}
  706. graph = G.Graph()
  707. # apply graph_opt_level in dump
  708. if self._graph_opt_level is not None:
  709. graph.options.graph_opt_level = self._graph_opt_level
  710. for i, h in enumerate(self._arg_bindings):
  711. info = self._tinfo[h]
  712. h2v[h] = graph.make_h2d(
  713. dtype=info.dtype,
  714. device=dumped_device(info),
  715. shape=info.shape or (1,),
  716. name=info.name if without_arg_names and info.name else arg_names[i],
  717. )
  718. for k, h in self._kwarg_bindings.items():
  719. info = self._tinfo[h]
  720. h2v[h] = graph.make_h2d(
  721. dtype=info.dtype,
  722. device=dumped_device(info),
  723. shape=info.shape or (1,),
  724. name=k,
  725. )
  726. for op, ihandles, ohandles in self._seq:
  727. if isinstance(op, str) and op == "Const":
  728. assert len(ihandles) == 0
  729. (h,) = ohandles
  730. info = self._tinfo[h]
  731. if h not in h2v:
  732. assert info.external
  733. assert info.bound_data
  734. h2v[h] = graph.make_const(
  735. info.bound_data.numpy(),
  736. dtype=info.dtype,
  737. device=info.device,
  738. name=info.name,
  739. )
  740. continue
  741. ivars = []
  742. for h in ihandles:
  743. info = self._tinfo[h]
  744. if h not in h2v:
  745. assert info.external
  746. assert info.bound_data
  747. h2v[h] = graph.make_const(
  748. info.bound_data.numpy(),
  749. dtype=info.dtype,
  750. device=dumped_device(info),
  751. name=info.name,
  752. )
  753. ivars.append(h2v[h])
  754. if isinstance(op, BackwardGraph):
  755. ovars = G.apply_backward_varnode(op, *ivars)
  756. else:
  757. if isinstance(op, BatchNorm):
  758. assert (
  759. op.fwd_mode == BatchNorm.FwdMode.INFERENCE
  760. ), "can not dump BatchNorm in training mode, maybe you forget to do model.eval()?"
  761. ovars = G.apply_normal_varnode(op, *ivars)
  762. AutoNaming.record_opnode(ovars[0].op)
  763. assert len(ovars) == len(ohandles)
  764. h2v.update(zip(ohandles, ovars))
  765. for i in ohandles:
  766. name = AutoNaming.get_var_name(i)
  767. if name is not None:
  768. h2v[i].name = name
  769. AutoNaming.remove_duplicate_names()
  770. dest_vars = []
  771. for i, h in enumerate(self._output_bindings):
  772. v = h2v[h]
  773. if output_names:
  774. v.name = output_names[i]
  775. dest_vars.append(v)
  776. if optimize_for_inference:
  777. dest_vars = G.optimize_for_inference(dest_vars, **kwargs)
  778. if isinstance(file, str):
  779. permission = "wb" if append == False else "ab"
  780. file = open(file, permission)
  781. dump_content, dump_info = G.dump_graph(
  782. dest_vars,
  783. keep_var_name=keep_var_name,
  784. keep_opr_name=keep_opr_name,
  785. keep_param_name=keep_param_name,
  786. keep_opr_priority=keep_opr_priority,
  787. strip_info_file=strip_info_file,
  788. append_json=append_json,
  789. )
  790. file.write(dump_content)
  791. return dump_info
  792. def _process_inputs(self, *args, **kwargs):
  793. if self._untraced:
  794. self._inputs_to_restore = []
  795. def record_input(x):
  796. if x is None:
  797. return
  798. h, info = self._new_handle()
  799. info.external = False
  800. info.name = x.c_name
  801. info.device = x.device
  802. info.dtype = x.dtype
  803. info.shape = x.numpy().shape
  804. x._mixin_handle = h
  805. x._recording = True
  806. x._trace_mixin_info = info
  807. self._inputs_to_restore.append(x)
  808. return h
  809. self._arg_bindings = []
  810. for i, x in enumerate(args):
  811. if not isinstance(x, RawTensor):
  812. raise TypeError(
  813. "positional arguments should all be tensor "
  814. "but args[%d] cannot be recognized as one" % i
  815. )
  816. self._arg_bindings.append(record_input(x))
  817. self._kwarg_bindings = {}
  818. for k, x in kwargs.items():
  819. if isinstance(x, RawTensor):
  820. self._kwarg_bindings[k] = record_input(x)
  821. else:
  822. if len(args) != len(self._arg_bindings):
  823. raise TraceMismatchError("positional argument length mismatch")
  824. self._tensor_remaps = {}
  825. for i, (h, x) in enumerate(zip(self._arg_bindings, args)):
  826. if not isinstance(x, RawTensor):
  827. raise TypeError(
  828. "positional arguments should all be tensor "
  829. "but args[%d] cannot be recognized as one" % i
  830. )
  831. info = self._tinfo[h]
  832. if x.dtype != info.dtype:
  833. raise TypeError("args[%d].dtype different from last time" % i)
  834. if x.device != info.device:
  835. raise TypeError("args[%d].device different from last time" % i)
  836. info.data_setter.set_value(x._dev_tensor())
  837. self._tensor_remaps[x._handle] = CompiledTensorProxy(h)
  838. kwargs_tensors = {}
  839. for k, x in kwargs.items():
  840. if isinstance(x, RawTensor):
  841. kwargs_tensors[k] = x
  842. if set(kwargs_tensors) != set(self._kwarg_bindings):
  843. too_many = set(kwargs_tensors) - set(self._kwarg_bindings)
  844. too_few = set(self._kwarg_bindings) - set(kwargs_tensors)
  845. if too_many:
  846. raise TraceMismatchError(
  847. "keyword arguments found to be tensor this time "
  848. "but were non-tensor previously: %s" % " ".join(too_many)
  849. )
  850. if too_few:
  851. raise TraceMismatchError(
  852. "keyword arguments found to be non-tensor this time "
  853. "but were tensor previously: %s" % " ".join(too_few)
  854. )
  855. for k, h in self._kwarg_bindings.items():
  856. x = kwargs_tensors[k]
  857. info = self._tinfo[h]
  858. if x.dtype != info.dtype:
  859. raise TypeError("kwargs[%s].dtype different from last time" % k)
  860. if x.device != info.device:
  861. raise TypeError("kwargs[%s].device different from last time" % k)
  862. info.data_setter.set_value(x._dev_tensor())
  863. self._tensor_remaps[x._handle] = CompiledTensorProxy(h)
  864. def _process_outputs(self, outputs):
  865. output_names = None
  866. if isinstance(outputs, collections.abc.Mapping):
  867. output_names, outputs = zip(*sorted(outputs.items()))
  868. elif not isinstance(outputs, collections.abc.Sequence):
  869. outputs = (outputs,)
  870. if not self._untraced:
  871. if output_names != self._output_names:
  872. too_many = set(output_names) - set(self._output_names)
  873. too_few = set(self._output_names) - set(output_names)
  874. if too_many:
  875. raise TraceMismatchError(
  876. "output has more keys than last time: %s" % " ".join(too_many)
  877. )
  878. if too_few:
  879. raise TraceMismatchError(
  880. "output has less keys than last time: %s" % " ".join(too_few)
  881. )
  882. if len(outputs) != len(self._output_bindings):
  883. raise TraceMismatchError("output size differs from last time")
  884. else:
  885. self._output_names = output_names
  886. self._output_bindings = []
  887. for i, x in enumerate(outputs):
  888. if not isinstance(x, RawTensor):
  889. raise TypeError("every item of return value should be tensor")
  890. if self._untraced:
  891. h = x._mixin_handle
  892. if h < 0:
  893. raise RuntimeError("output is not computed from inputs")
  894. self._output_bindings.append(h)
  895. else:
  896. h = x._mixin_handle
  897. if h not in self._output_handles:
  898. raise RuntimeError("output is not computed from inputs")
  899. if h != self._output_bindings[i]:
  900. raise TraceMismatchError(
  901. "retval[%s] is a different tensor than last time"
  902. % (output_names and output_names[i] or i)
  903. )
  904. def get_profile(self):
  905. """
  906. Get profiling result for compiled trace.
  907. :return: a json compatible object.
  908. """
  909. if not self._profiler:
  910. raise RuntimeError("trace is not set with profiling=True")
  911. return json.loads(self._profiler.get())
  912. def __del__(self):
  913. for x in self._tinfo:
  914. if getattr(x, "bound_data", None):
  915. x.bound_data = None
  916. def trace(self, *args, **kwargs):
  917. raise NotImplementedError(
  918. "trace is deemed unbeneficial with the new "
  919. "tracing mechanism. You should alwasy use __call__."
  920. )
  921. class CompiledTensorProxy:
  922. """
  923. Duck-typed RawTensor
  924. """
  925. def __init__(self, handle):
  926. self.__handle = handle
  927. self._isscalar = False
  928. self.__info = active_trace._tinfo[handle]
  929. self.__shape = None
  930. self.__data = None
  931. self.__value = None
  932. @property
  933. def dtype(self):
  934. return self.__info.varnode.dtype
  935. @property
  936. def device(self):
  937. return self.__info.varnode.device
  938. @property
  939. def shape(self):
  940. if self._isscalar:
  941. return ()
  942. if self.__shape is None:
  943. if self.__info.shape_read:
  944. self.__shape = self.__info.shape_reader.get_value().shape
  945. elif self.__info.data_read:
  946. self.__shape = self._dev_tensor().shape
  947. else:
  948. # c++ will throw TraceReadError
  949. return None
  950. return self.__shape
  951. def numpy(self):
  952. if self.__value is None:
  953. if self.__info.value_read:
  954. self.__value = self.__info.value_reader.get_value()
  955. elif self.__info.data_read:
  956. self.__value = self._dev_tensor().numpy()
  957. else:
  958. # c++ will throw TraceReadError
  959. return None
  960. # c++ side will handle scalar case
  961. return self.__value
  962. def _dev_tensor(self):
  963. if self.__data is None:
  964. if not self.__info.data_read:
  965. # c++ will throw TraceReadError
  966. return None
  967. self.__data = self.__info.data_reader.get_value()
  968. return self.__data
  969. def __del__(self):
  970. if self.__info.shape_read and self.__shape is not None:
  971. self.__info.shape_reader.drop_value()
  972. if self.__info.value_read and self.__value is not None:
  973. self.__info.value_reader.drop_value()
  974. if self.__info.data_read and self.__data is not None:
  975. self.__info.data_reader.drop_value()
  976. def assign_raw_tensor(lhs, rhs):
  977. lhs.__init__(rhs)
  978. def apply_symbolic_mode(op: OpDef, *args: RawTensor):
  979. graph = active_trace._lazy_eval_graph
  980. ivars = []
  981. for x in args:
  982. var = getattr(x, "_varnode", None)
  983. if var:
  984. ivars.append(var)
  985. else:
  986. data_setter = G.InputNode(
  987. device=x.device,
  988. dtype=x.dtype,
  989. shape=x.numpy().shape or (1,),
  990. graph=graph,
  991. use_static_shape=True,
  992. )
  993. var = data_setter.outputs[0]
  994. ivars.append(var)
  995. data_setter.set_value(x._dev_tensor())
  996. require_links = type(op) in _io_op_types
  997. if require_links and active_trace._lazy_eval_links:
  998. assert len(ivars) > 0, "op should has at least one input"
  999. opnode = G.VirtualDepNode(
  1000. [ivars[0], *active_trace._lazy_eval_links],
  1001. str(active_trace._lazy_eval_links[0].device),
  1002. )
  1003. ivars[0] = opnode.outputs[0]
  1004. active_trace._lazy_eval_links = (ivars[0],)
  1005. if isinstance(op, BackwardGraph):
  1006. ovars = G.apply_backward_varnode(op, *ivars)
  1007. else:
  1008. ovars = G.apply_normal_varnode(op, *ivars)
  1009. outputs = [RawTensor(o) for o in ovars]
  1010. if require_links:
  1011. active_trace._lazy_eval_links = (G.VarNode(outputs[0]._varnode),)
  1012. return outputs
  1013. def apply_const_symbolic_mode(value, dtype, device, name):
  1014. graph = active_trace._lazy_eval_graph
  1015. # don't need to unset tracing
  1016. # because varnode construction will ignore tracing flag
  1017. ret = RawTensor(graph.make_const(value, dtype=dtype, device=device, name=name))
  1018. if np.array(value).ndim == 0:
  1019. setscalar(ret)
  1020. return (ret,)
  1021. def apply_compiled_mode(op: OpDef, *args: RawTensor):
  1022. if skip_tracing:
  1023. args = [
  1024. RawTensor(x._dev_tensor()) if x.__class__ is CompiledTensorProxy else x
  1025. for x in args
  1026. ]
  1027. unset_tracing()
  1028. ret = apply(op, *args)
  1029. set_tracing()
  1030. return ret
  1031. return active_trace._apply_op(op, args)
  1032. def apply_const_compiled_mode(value, dtype, device, is_const, no_cache, name):
  1033. if skip_tracing:
  1034. args = [
  1035. RawTensor(x._dev_tensor()) if x.__class__ is CompiledTensorProxy else x
  1036. for x in args
  1037. ]
  1038. unset_tracing()
  1039. ret = RawTensor(value, dtype, device, False, name)
  1040. set_tracing()
  1041. return ret
  1042. return active_trace._apply_const(value, dtype, device)
  1043. def apply_with_tracing(op: OpDef, *args: RawTensor):
  1044. if hasattr(op, "scope"):
  1045. op.scope = AutoNaming.get_scope()
  1046. if active_trace._symbolic:
  1047. outputs = apply_symbolic_mode(op, *args)
  1048. else:
  1049. unset_tracing()
  1050. outputs = apply(op, *args)
  1051. set_tracing()
  1052. active_trace._record_op(op, args, outputs)
  1053. return list(outputs)
  1054. def apply_const_with_tracing(value, dtype, device, is_const, no_cache, name):
  1055. if active_trace._symbolic:
  1056. outputs = apply_const_symbolic_mode(value, dtype, device, name)
  1057. else:
  1058. unset_tracing()
  1059. outputs = (RawTensor(value, dtype, device, False, name),)
  1060. set_tracing()
  1061. active_trace._record_const(outputs)
  1062. return list(outputs)

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