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

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

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