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

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

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