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

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

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