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

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

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