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

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

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