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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. import collections
  2. import contextlib
  3. import functools
  4. import itertools
  5. import json
  6. import typing
  7. import warnings
  8. import weakref
  9. import numpy as np
  10. from ..core._imperative_rt import GraphProfiler
  11. from ..core._imperative_rt.ops import OprAttr
  12. from ..core.ops.special import Const
  13. from ..core.tensor import megbrain_graph as G
  14. from ..core.tensor.core import OpBase, TensorBase, TensorWrapperBase, apply
  15. from ..core.tensor.raw_tensor import OpDef, RawTensor, as_raw_tensor
  16. from ..core.tensor.tensor import Tensor
  17. from .sublinear_memory_config import SublinearMemoryConfig
  18. class TraceMismatchError(RuntimeError):
  19. pass
  20. active_trace = None
  21. skip_tracing = False
  22. @contextlib.contextmanager
  23. def exclude_from_trace():
  24. global skip_tracing
  25. if skip_tracing:
  26. yield
  27. return
  28. try:
  29. skip_tracing = True
  30. if active_trace is not None:
  31. active_trace._begin_excluded_region()
  32. yield
  33. finally:
  34. skip_tracing = False
  35. class TensorInfo:
  36. __slots__ = (
  37. # collected attributes
  38. "external",
  39. "exported",
  40. "data_read",
  41. "shape_read",
  42. "value_read",
  43. "device",
  44. "dtype",
  45. "shape",
  46. "bound_data",
  47. # resources for execution
  48. "varnode",
  49. "data_setter",
  50. "shape_reader",
  51. "value_reader",
  52. "data_reader",
  53. )
  54. def __init__(self):
  55. self.exported = None
  56. self.data_read = None
  57. self.shape_read = None
  58. self.value_read = None
  59. self.bound_data = None
  60. self.data_setter = None
  61. self.shape_reader = None
  62. self.value_reader = None
  63. self.data_reader = None
  64. class trace:
  65. def __new__(cls, *args, **kwargs):
  66. if not args:
  67. return functools.partial(cls, **kwargs)
  68. self = super().__new__(cls)
  69. self.__init__(*args, **kwargs)
  70. return self
  71. def __init__(
  72. self,
  73. function,
  74. symbolic=False,
  75. capture_as_const=False,
  76. sublinear_memory_config: SublinearMemoryConfig = None,
  77. profiling: bool = False,
  78. ):
  79. self.__wrapped__ = function
  80. self._symbolic = symbolic
  81. self._capture_as_const = capture_as_const
  82. self._sublinear_memory_config = sublinear_memory_config
  83. self._profiling = profiling
  84. self._profiler = None
  85. self._untraced = True
  86. self._tinfo = [] # handle -> TensorInfo
  87. self._seq = []
  88. self._pc = 0
  89. self._graph = None
  90. self._need_reset_nodes = None
  91. self._lazy_eval_graph = None
  92. self._lazy_eval_tensors = weakref.WeakSet()
  93. self._active_tensors = weakref.WeakSet()
  94. self._tensor_remaps = None
  95. self._inputs_to_restore = None
  96. self._arg_bindings = None
  97. self._kwarg_bindings = None
  98. self._output_bindings = None
  99. self._output_names = None
  100. def _new_handle(self):
  101. handle = len(self._tinfo)
  102. info = TensorInfo()
  103. self._tinfo.append(info)
  104. return handle, info
  105. def _apply_op(self, op, args):
  106. assert not self._untraced
  107. # check against trace
  108. if self._pc >= len(self._seq):
  109. raise TraceMismatchError("trace should end here, but more op observed")
  110. record = self._seq[self._pc]
  111. op_, ihandles, ohandles = record
  112. if op != op_:
  113. # FIXME: will be removed once better rng implementation is done
  114. if isinstance(op, OprAttr) and (
  115. op.type in ("UniformRNG", "GaussianRNG") and op.type == op_.type
  116. ):
  117. if op.param[8:] != op_.param[8:]:
  118. raise TraceMismatchError("op different from last time")
  119. else:
  120. raise TraceMismatchError("op different from last time")
  121. if len(ihandles) != len(args):
  122. raise TraceMismatchError("op input size different from last time")
  123. for h, x in zip(ihandles, args):
  124. info = self._tinfo[h]
  125. if info.external:
  126. if (
  127. x.__class__ is CompiledTensorProxy
  128. and not self._tinfo[x._CompiledTensorProxy__handle].exported
  129. ):
  130. raise TraceMismatchError(
  131. "failed to capture: input was an external tensor "
  132. "last time, got an internal tensor this time"
  133. )
  134. if info.bound_data:
  135. if x.__class__ is CompiledTensorProxy:
  136. raise TraceMismatchError(
  137. "const capture violated: was an external tensor "
  138. "last time, got an internal tensor this time"
  139. )
  140. if x._handle != info.bound_data._handle:
  141. if not np.array_equal(
  142. x.numpy(), info.bound_data.numpy(), equal_nan=True
  143. ):
  144. raise TraceMismatchError(
  145. "const capture violated: got "
  146. "a different tensor this time"
  147. )
  148. else:
  149. if info.dtype != x.dtype:
  150. raise TraceMismatchError(
  151. "failed to capture: different dtype from last time"
  152. )
  153. if info.device != x.device:
  154. raise TraceMismatchError(
  155. "failed to capture: different device from last time"
  156. )
  157. info.data_setter.set_value(x._dev_tensor())
  158. else:
  159. if x.__class__ is not CompiledTensorProxy:
  160. if x not in self._tensor_remaps:
  161. raise TraceMismatchError(
  162. "unexpected capture: trying to use an external tensor as "
  163. "input, but that input was an internal tensor last time"
  164. )
  165. else:
  166. x = self._tensor_remaps[x]
  167. if x._CompiledTensorProxy__handle != h:
  168. raise TraceMismatchError(
  169. "mis-wiring: input edge to an data flow "
  170. "graph node is different from last time"
  171. )
  172. self._pc += 1
  173. outputs = tuple([CompiledTensorProxy(h) for h in ohandles])
  174. self._active_tensors.update(outputs)
  175. return outputs
  176. def _record_op(self, op, inputs, outputs):
  177. if skip_tracing:
  178. for x in inputs:
  179. h = getattr(x, "_TraceMixin__handle", None)
  180. if h is not None:
  181. self._tinfo[h].data_read = True
  182. return
  183. ihandles = []
  184. for x in inputs:
  185. h = getattr(x, "_TraceMixin__handle", None)
  186. if h is None or (not self._capture_as_const and self._tinfo[h].exported):
  187. h, info = self._new_handle()
  188. info.external = True
  189. info.device = x.device
  190. info.dtype = x.dtype
  191. info.shape = x.shape
  192. if self._capture_as_const:
  193. info.bound_data = x
  194. ihandles.append(h)
  195. ohandles = []
  196. for x in outputs:
  197. h, info = self._new_handle()
  198. ohandles.append(h)
  199. info.external = False
  200. TraceMixin._TraceMixin__inject(x, h)
  201. self._seq.append((op, tuple(ihandles), tuple(ohandles)))
  202. self._active_tensors.update(outputs)
  203. def _record_const(self, op, outputs):
  204. pass
  205. @contextlib.contextmanager
  206. def _setup(self):
  207. global active_trace
  208. if active_trace:
  209. raise NotImplementedError("sorry, not implemented: nested trace")
  210. active_trace = self
  211. if self._untraced:
  212. apply.enable(apply_with_tracing)
  213. apply.enable(apply_const_with_tracing)
  214. if self._symbolic:
  215. apply.enable(apply_symbolic_mode)
  216. apply.enable(apply_const_symbolic_mode)
  217. self._lazy_eval_graph = G.Graph()
  218. else:
  219. apply.enable(apply_compiled_mode)
  220. if self._graph is None:
  221. self._compile()
  222. self._graph.execute()
  223. yield
  224. escaped_tensors = tuple(self._active_tensors)
  225. self._active_tensors.clear()
  226. if self._untraced:
  227. for x in escaped_tensors:
  228. info = self._tinfo[x._TraceMixin__handle]
  229. info.data_read = True
  230. x._TraceMixin__restore()
  231. if self._inputs_to_restore:
  232. for x in self._inputs_to_restore:
  233. x._TraceMixin__restore()
  234. if self._symbolic:
  235. # eval lazy eval tensors
  236. lazy_eval_tensors = tuple(self._lazy_eval_tensors)
  237. if lazy_eval_tensors:
  238. readers = [
  239. G.OutputNode(x._LazyEvalTensor__varnode).outputs[0]
  240. for x in lazy_eval_tensors
  241. ]
  242. self._apply_graph_options(self._lazy_eval_graph)
  243. self._lazy_eval_graph.compile(*readers)
  244. self._lazy_eval_graph()
  245. for r, x in zip(readers, lazy_eval_tensors):
  246. assign_raw_tensor(x, as_raw_tensor(r.op.get_value()))
  247. self._lazy_eval_graph = None
  248. self._lazy_eval_tensors = None
  249. self._untraced = False
  250. else:
  251. if self._pc != len(self._seq):
  252. raise TraceMismatchError("premature end")
  253. for x in escaped_tensors:
  254. assign_raw_tensor(x, as_raw_tensor(x._dev_tensor()))
  255. self._graph.wait()
  256. self._reset_exec_env()
  257. self._pc = 0
  258. self._tensor_remaps = None
  259. apply.disable(apply_with_tracing)
  260. apply.disable(apply_const_with_tracing)
  261. apply.disable(apply_symbolic_mode)
  262. apply.disable(apply_const_symbolic_mode)
  263. apply.disable(apply_compiled_mode)
  264. active_trace = None
  265. def _begin_excluded_region(self):
  266. if self._capture_as_const:
  267. raise RuntimeError(
  268. "exclude_from_trace cannot be used with capture_as_const"
  269. )
  270. if self._untraced:
  271. # conditionally reading a compiled tensor in excluded region
  272. # is permitted, so we have to assume every tensor might be read
  273. for x in self._active_tensors:
  274. info = self._tinfo[x._TraceMixin__handle]
  275. info.exported = True
  276. info.data_read = True
  277. def _apply_graph_options(self, graph):
  278. # sublinear
  279. if self._sublinear_memory_config is not None:
  280. graph.options.enable_sublinear_memory_opt = True
  281. sublinear_config = graph.options.sublinear_mem_config
  282. sublinear_config.lb_memory = self._sublinear_memory_config.lb_memory
  283. sublinear_config.genetic_nr_iter = (
  284. self._sublinear_memory_config.genetic_nr_iter
  285. )
  286. sublinear_config.genetic_pool_size = (
  287. self._sublinear_memory_config.genetic_pool_size
  288. )
  289. sublinear_config.thresh_nr_try = self._sublinear_memory_config.thresh_nr_try
  290. sublinear_config.num_worker = self._sublinear_memory_config.num_worker
  291. if self._profiling:
  292. self._profiler = GraphProfiler(graph)
  293. def _compile(self):
  294. graph = self._graph = G.Graph()
  295. graph.options.no_force_inplace = True
  296. self._apply_graph_options(graph)
  297. # graph.options.graph_opt_level = 0
  298. need_reset_nodes = self._need_reset_nodes = []
  299. # links enforce ordering of I/O nodes
  300. links = ()
  301. if self._capture_as_const:
  302. for h in itertools.chain(self._arg_bindings, self._kwarg_bindings.values()):
  303. info = self._tinfo[h]
  304. opnode = info.data_setter = G.InputNode(
  305. device=info.device, dtype=info.dtype, shape=info.shape, graph=graph
  306. )
  307. need_reset_nodes.append(opnode)
  308. info.varnode = opnode.outputs[0]
  309. links += opnode.outputs[1:]
  310. for op, ihandles, ohandles in self._seq:
  311. ivars = []
  312. readers = []
  313. for h in ihandles:
  314. info = self._tinfo[h]
  315. if not hasattr(info, "varnode"):
  316. assert info.external
  317. if info.bound_data:
  318. info.varnode = graph.make_const(info.bound_data._dev_tensor())
  319. else:
  320. opnode = info.data_setter = G.InputNode(
  321. *links,
  322. device=info.device,
  323. dtype=info.dtype,
  324. shape=info.shape,
  325. graph=graph,
  326. )
  327. need_reset_nodes.append(opnode)
  328. info.varnode, *links = opnode.outputs
  329. ivars.append(info.varnode)
  330. ovars = apply(op, *ivars)
  331. assert len(ovars) == len(ohandles)
  332. for h, v in zip(ohandles, ovars):
  333. info = self._tinfo[h]
  334. info.varnode = v
  335. def add_reader(opnode):
  336. nonlocal links
  337. need_reset_nodes.append(opnode)
  338. readers.append(opnode.outputs[0])
  339. links = opnode.outputs
  340. if info.data_read:
  341. # Shape can be obtained from data so doesn't need its own
  342. # output node. On the other hand, value is read separately
  343. # to leverage eager h2d copy
  344. info.shape_read = False
  345. opnode = info.data_reader = G.OutputNode(v, *links)
  346. add_reader(opnode)
  347. if info.value_read:
  348. opnode = info.value_reader = G.ValueOutputNode(v, *links)
  349. add_reader(opnode)
  350. if info.shape_read:
  351. opnode = info.shape_reader = G.AttrOutputNode(v, *links)
  352. add_reader(opnode)
  353. graph.compile(*readers)
  354. def _reset_exec_env(self):
  355. for opnode in self._need_reset_nodes:
  356. opnode.reset()
  357. def _require_shape(self, handle):
  358. info = self._tinfo[handle]
  359. info.shape_read = True
  360. def _require_value(self, handle):
  361. info = self._tinfo[handle]
  362. info.value_read = True
  363. def _require_data(self, handle):
  364. info = self._tinfo[handle]
  365. info.data_read = True
  366. def __call__(self, *args, **kwargs):
  367. with self._setup():
  368. if self._capture_as_const:
  369. self._process_inputs(*args, **kwargs)
  370. outputs = self.__wrapped__(*args, **kwargs)
  371. if self._capture_as_const:
  372. self._process_outputs(outputs)
  373. return outputs
  374. def dump(self, file, *, arg_names=None, output_names=None):
  375. if not self._capture_as_const:
  376. raise ValueError(
  377. "you must specify capture_as_const=True at __init__ to use dump"
  378. )
  379. if self._untraced:
  380. raise RuntimeError("should run at least once before calling dump")
  381. if self._output_names and output_names:
  382. raise TypeError(
  383. "cannot specify output_names when output is already in dict format"
  384. )
  385. if output_names and not isinstance(output_names, collections.Sequence):
  386. output_names = (output_names,)
  387. if output_names and len(output_names) != len(self._output_bindings):
  388. raise ValueError("wrong number of output_names")
  389. if arg_names and not isinstance(arg_names, collections.Sequence):
  390. arg_names = (arg_names,)
  391. if arg_names and len(arg_names) != len(self._arg_bindings):
  392. raise ValueError("wrong number of arg_names")
  393. output_names = output_names or self._output_names
  394. h2v = {}
  395. graph = G.Graph()
  396. for i, h in enumerate(self._arg_bindings):
  397. info = self._tinfo[h]
  398. h2v[h] = graph.make_h2d(
  399. dtype=info.dtype,
  400. device=info.device,
  401. shape=info.shape,
  402. name=arg_names[i] if arg_names else None,
  403. )
  404. for k, h in self._kwarg_bindings.items():
  405. info = self._tinfo[h]
  406. h2v[h] = graph.make_h2d(
  407. dtype=info.dtype, device=info.device, shape=info.shape, name=k
  408. )
  409. for op, ihandles, ohandles in self._seq:
  410. ivars = []
  411. for h in ihandles:
  412. info = self._tinfo[h]
  413. if h not in h2v:
  414. assert info.external
  415. assert info.bound_data
  416. h2v[h] = graph.make_const(info.bound_data._dev_tensor())
  417. ivars.append(h2v[h])
  418. ovars = apply(op, *ivars)
  419. assert len(ovars) == len(ohandles)
  420. h2v.update(zip(ohandles, ovars))
  421. dest_vars = []
  422. for i, h in enumerate(self._output_bindings):
  423. v = h2v[h]
  424. if output_names:
  425. v.name = output_names[i]
  426. dest_vars.append(v)
  427. if isinstance(file, str):
  428. file = open(file, "wb")
  429. file.write(G.dump(*dest_vars))
  430. def _process_inputs(self, *args, **kwargs):
  431. if self._untraced:
  432. self._inputs_to_restore = []
  433. def record_input(x):
  434. if x is None:
  435. return
  436. h, info = self._new_handle()
  437. info.external = False
  438. info.device = x.device
  439. info.dtype = x.dtype
  440. info.shape = x.shape
  441. TraceMixin._TraceMixin__inject(x, h)
  442. self._inputs_to_restore.append(x)
  443. return h
  444. self._arg_bindings = []
  445. for i, x in enumerate(args):
  446. x = find_raw_tensor(x)
  447. if x is None:
  448. raise TypeError(
  449. "positional arguments should all be tensor "
  450. "but args[%d] cannot be recognized as one" % i
  451. )
  452. self._arg_bindings.append(record_input(x))
  453. self._kwarg_bindings = {}
  454. for k, x in kwargs.items():
  455. x = find_raw_tensor(x)
  456. if x is not None:
  457. self._kwarg_bindings[k] = record_input(x)
  458. else:
  459. if len(args) != len(self._arg_bindings):
  460. raise TraceMismatchError("positional argument length mismatch")
  461. self._tensor_remaps = {}
  462. for i, (h, x) in enumerate(zip(self._arg_bindings, args)):
  463. x = find_raw_tensor(x)
  464. if x is None:
  465. raise TypeError(
  466. "positional arguments should all be tensor "
  467. "but args[%d] cannot be recognized as one" % i
  468. )
  469. info = self._tinfo[h]
  470. if x.dtype != info.dtype:
  471. raise TypeError("args[%d].dtype different from last time" % i)
  472. if x.device != info.device:
  473. raise TypeError("args[%d].device different from last time" % i)
  474. info.data_setter.set_value(x._dev_tensor())
  475. self._tensor_remaps[x] = CompiledTensorProxy(h)
  476. kwargs_tensors = {}
  477. for k, x in kwargs.items():
  478. x = find_raw_tensor(x)
  479. if x is not None:
  480. kwargs_tensors[k] = x
  481. if set(kwargs_tensors) != set(self._kwarg_bindings):
  482. too_many = set(kwargs_tensors) - set(self._kwarg_bindings)
  483. too_few = set(self._kwarg_bindings) - set(kwargs_tensors)
  484. if too_many:
  485. raise TraceMismatchError(
  486. "keyword arguments found to be tensor this time "
  487. "but were non-tensor previously: %s" % " ".join(too_many)
  488. )
  489. if too_few:
  490. raise TraceMismatchError(
  491. "keyword arguments found to be non-tensor this time "
  492. "but were tensor previously: %s" % " ".join(too_few)
  493. )
  494. for k, h in self._kwarg_bindings.items():
  495. x = kwargs_tensors[k]
  496. info = self._tinfo[h]
  497. if x.dtype != info.dtype:
  498. raise TypeError("kwargs[%s].dtype different from last time" % k)
  499. if x.device != info.device:
  500. raise TypeError("kwargs[%s].device different from last time" % k)
  501. info.data_setter.set_value(x._dev_tensor())
  502. self._tensor_remaps[x] = CompiledTensorProxy(h)
  503. def _process_outputs(self, outputs):
  504. output_names = None
  505. if isinstance(outputs, collections.Mapping):
  506. output_names, outputs = zip(*sorted(outputs.items()))
  507. elif not isinstance(outputs, collections.Sequence):
  508. outputs = (outputs,)
  509. if not self._untraced:
  510. if output_names != self._output_names:
  511. too_many = set(output_names) - set(self._output_names)
  512. too_few = set(self._output_names) - set(output_names)
  513. if too_many:
  514. raise TraceMismatchError(
  515. "output has more keys than last time: %s" % " ".join(too_many)
  516. )
  517. if too_few:
  518. raise TraceMismatchError(
  519. "output has less keys than last time: %s" % " ".join(too_few)
  520. )
  521. if len(outputs) != len(self._output_bindings):
  522. raise TraceMismatchError("output size differs from last time")
  523. else:
  524. self._output_names = output_names
  525. self._output_bindings = []
  526. for i, x in enumerate(outputs):
  527. x = find_raw_tensor(x)
  528. if x is None:
  529. raise TypeError("every item of return value should be tensor")
  530. if self._untraced:
  531. if not isinstance(x, TraceMixin):
  532. raise RuntimeError("output is not computed from inputs")
  533. h = x._TraceMixin__handle
  534. self._output_bindings.append(h)
  535. else:
  536. if not isinstance(x, CompiledTensorProxy):
  537. raise RuntimeError("output is not computed from inputs")
  538. h = x._CompiledTensorProxy__handle
  539. if h != self._output_bindings[i]:
  540. raise TraceMismatchError(
  541. "retval[%s] is a different tensor than last time"
  542. % (output_names and output_names[i] or i)
  543. )
  544. def get_profile(self):
  545. """
  546. Get profiling result for compiled trace.
  547. :return: a json compatible object.
  548. """
  549. if not self._profiler:
  550. raise RuntimeError("trace is not set with profiling=True")
  551. return json.loads(self._profiler.get())
  552. class CompiledTensorProxy(RawTensor):
  553. """
  554. Duck-typed RawTensor
  555. """
  556. def __init__(self, handle):
  557. self.__handle = handle
  558. self.__info = active_trace._tinfo[handle]
  559. self.__shape = None
  560. self.__data = None
  561. self.__value = None
  562. @property
  563. def dtype(self):
  564. return self.__info.varnode.dtype
  565. @property
  566. def device(self):
  567. return self.__info.varnode.device
  568. @property
  569. def shape(self):
  570. if self.__shape is None:
  571. if self.__info.shape_read:
  572. self.__shape = self.__info.shape_reader.get_value().shape
  573. elif self.__info.data_read:
  574. self.__shape = self._dev_tensor().shape
  575. else:
  576. raise TraceMismatchError("shape of this tensor is not read in trace")
  577. return self.__shape
  578. def numpy(self):
  579. if self.__value is None:
  580. if self.__info.value_read:
  581. self.__value = self.__info.value_reader.get_value()
  582. elif self.__info.data_read:
  583. self.__value = self._dev_tensor().numpy()
  584. else:
  585. raise TraceMismatchError("value of this tensor is not read in trace")
  586. return self.__value
  587. def _dev_tensor(self):
  588. if self.__data is None:
  589. if not self.__info.data_read:
  590. raise TraceMismatchError("raw data of this tensor is not read in trace")
  591. self.__data = self.__info.data_reader.get_value()
  592. return self.__data
  593. def __del__(self):
  594. if self.__info.shape_read and self.__shape is not None:
  595. self.__info.shape_reader.drop_value()
  596. if self.__info.value_read and self.__value is not None:
  597. self.__info.value_reader.drop_value()
  598. if self.__info.data_read and self.__data is not None:
  599. self.__info.data_reader.drop_value()
  600. class LazyEvalTensor(RawTensor):
  601. def __init__(self, varnode):
  602. self.__varnode = varnode
  603. @property
  604. def dtype(self):
  605. return self.__varnode.dtype
  606. @property
  607. def device(self):
  608. return self.__varnode.device
  609. @property
  610. def shape(self):
  611. return self.__varnode.shape
  612. def numpy(self):
  613. return self.__varnode.value
  614. def _dev_tensor(self):
  615. raise RuntimeError("cannot access data during symbolic tracing")
  616. class TraceMixin:
  617. __subclass_cache = {}
  618. def __inject(self, handle):
  619. cache = __class__.__subclass_cache
  620. cls = self.__class__
  621. subcls = cache.get(cls)
  622. if subcls is None:
  623. subcls = cache[cls] = type("Traced" + cls.__name__, (__class__, cls), {})
  624. self.__class__ = subcls
  625. self.__handle = handle
  626. self.__cls = cls
  627. return self
  628. def __restore(self):
  629. cls = self.__cls
  630. del self.__handle
  631. del self.__cls
  632. self.__class__ = cls
  633. return self
  634. @property
  635. def shape(self):
  636. if not skip_tracing:
  637. active_trace._require_shape(self.__handle)
  638. return super().shape
  639. def numpy(self):
  640. if not skip_tracing:
  641. active_trace._require_value(self.__handle)
  642. return super().numpy()
  643. def _dev_tensor(self):
  644. if not skip_tracing:
  645. active_trace._require_data(self.__handle)
  646. return super()._dev_tensor()
  647. class TracedRawTensor(TraceMixin, RawTensor):
  648. pass
  649. class TracedLazyTensor(TraceMixin, LazyEvalTensor):
  650. pass
  651. def assign_raw_tensor(lhs, rhs):
  652. handle = rhs._handle
  653. rhs.__dict__.clear()
  654. lhs.__dict__.clear()
  655. lhs.__class__ = RawTensor
  656. lhs.__init__(handle)
  657. # this hook turns RawTensor into LazyEvalTensor
  658. @apply.register()
  659. def apply_symbolic_mode(op: OpDef, *args: RawTensor):
  660. graph = active_trace._lazy_eval_graph
  661. ivars = [
  662. getattr(x, "_LazyEvalTensor__varnode", None)
  663. or graph.make_const(x._dev_tensor())
  664. for x in args
  665. ]
  666. ovars = apply(op, *ivars)
  667. outputs = [LazyEvalTensor(v) for v in ovars]
  668. active_trace._lazy_eval_tensors.update(outputs)
  669. return outputs
  670. apply.disable(apply_symbolic_mode)
  671. @apply.register()
  672. def apply_const_symbolic_mode(op: Const, *args: RawTensor):
  673. graph = active_trace._lazy_eval_graph
  674. ret = LazyEvalTensor(graph.make_const(op.value, dtype=op.dtype, device=op.device))
  675. active_trace._lazy_eval_tensors.add(ret)
  676. return (ret,)
  677. apply.disable(apply_const_symbolic_mode)
  678. @apply.register()
  679. def apply_compiled_mode(op: OpDef, *args: RawTensor):
  680. if skip_tracing:
  681. args = [
  682. as_raw_tensor(x._dev_tensor()) if x.__class__ is CompiledTensorProxy else x
  683. for x in args
  684. ]
  685. return apply.super(op, *args)
  686. return active_trace._apply_op(op, args)
  687. apply.disable(apply_compiled_mode)
  688. # this hook injects TraceMixin
  689. @apply.register()
  690. def apply_with_tracing(op: OpDef, *args: RawTensor):
  691. outputs = apply.super(op, *args)
  692. active_trace._record_op(op, args, outputs)
  693. return outputs
  694. apply.disable(apply_with_tracing)
  695. @apply.register()
  696. def apply_const_with_tracing(op: Const, *args: RawTensor):
  697. outputs = apply.super(op, *args)
  698. active_trace._record_const(op, outputs)
  699. return outputs
  700. apply.disable(apply_const_with_tracing)
  701. class BrokenRawTensor(RawTensor):
  702. def __getattribute__(self, _):
  703. raise RuntimeError("broken due to misuse of tracing")
  704. def __setattr__(self, *_):
  705. raise RuntimeError("broken due to misuse of tracing")
  706. @functools.singledispatch
  707. def find_raw_tensor(x):
  708. return None
  709. @find_raw_tensor.register(RawTensor)
  710. def _(x):
  711. return x
  712. @find_raw_tensor.register(TensorWrapperBase)
  713. def _(x):
  714. x = getattr(x, "__wrapped__", None)
  715. if x is not None:
  716. return find_raw_tensor(x)
  717. @find_raw_tensor.register(Tensor)
  718. def _(x):
  719. x = getattr(x, "_data", None)
  720. if x is not None:
  721. return find_raw_tensor(x)

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