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

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

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