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

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

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