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

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

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