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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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. if self._capture_as_const:
  300. for h in itertools.chain(self._arg_bindings, self._kwarg_bindings.values()):
  301. info = self._tinfo[h]
  302. opnode = info.data_setter = G.InputNode(
  303. device=info.device, dtype=info.dtype, shape=info.shape, graph=graph
  304. )
  305. need_reset_nodes.append(opnode)
  306. info.varnode = opnode.outputs[0]
  307. links += opnode.outputs[1:]
  308. for op, ihandles, ohandles in self._seq:
  309. ivars = []
  310. readers = []
  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("wrong number of output_names")
  387. if arg_names and not isinstance(arg_names, collections.Sequence):
  388. arg_names = (arg_names,)
  389. if arg_names and len(arg_names) != len(self._arg_bindings):
  390. raise ValueError("wrong number of arg_names")
  391. output_names = output_names or self._output_names
  392. h2v = {}
  393. graph = G.Graph()
  394. for i, h in enumerate(self._arg_bindings):
  395. info = self._tinfo[h]
  396. h2v[h] = graph.make_h2d(
  397. dtype=info.dtype,
  398. device=info.device,
  399. shape=info.shape,
  400. name=arg_names[i] if arg_names else None,
  401. )
  402. for k, h in self._kwarg_bindings.items():
  403. info = self._tinfo[h]
  404. h2v[h] = graph.make_h2d(
  405. dtype=info.dtype, device=info.device, shape=info.shape, name=k
  406. )
  407. for op, ihandles, ohandles in self._seq:
  408. ivars = []
  409. for h in ihandles:
  410. info = self._tinfo[h]
  411. if h not in h2v:
  412. assert info.external
  413. assert info.bound_data
  414. h2v[h] = graph.make_const(info.bound_data._dev_tensor())
  415. ivars.append(h2v[h])
  416. ovars = apply(op, *ivars)
  417. assert len(ovars) == len(ohandles)
  418. h2v.update(zip(ohandles, ovars))
  419. dest_vars = []
  420. for i, h in enumerate(self._output_bindings):
  421. v = h2v[h]
  422. if output_names:
  423. v.name = output_names[i]
  424. dest_vars.append(v)
  425. if isinstance(file, str):
  426. file = open(file, "wb")
  427. file.write(G.dump(*dest_vars))
  428. def _process_inputs(self, *args, **kwargs):
  429. if self._untraced:
  430. self._inputs_to_restore = []
  431. def record_input(x):
  432. if x is None:
  433. return
  434. h, info = self._new_handle()
  435. info.external = False
  436. info.device = x.device
  437. info.dtype = x.dtype
  438. info.shape = x.shape
  439. TraceMixin._TraceMixin__inject(x, h)
  440. self._inputs_to_restore.append(x)
  441. return h
  442. self._arg_bindings = []
  443. for i, x in enumerate(args):
  444. x = find_raw_tensor(x)
  445. if x is None:
  446. raise TypeError(
  447. "positional arguments should all be tensor "
  448. "but args[%d] cannot be recognized as one" % i
  449. )
  450. self._arg_bindings.append(record_input(x))
  451. self._kwarg_bindings = {}
  452. for k, x in kwargs.items():
  453. x = find_raw_tensor(x)
  454. if x is not None:
  455. self._kwarg_bindings[k] = record_input(x)
  456. else:
  457. if len(args) != len(self._arg_bindings):
  458. raise TraceMismatchError("positional argument length mismatch")
  459. self._tensor_remaps = {}
  460. for i, (h, x) in enumerate(zip(self._arg_bindings, args)):
  461. x = find_raw_tensor(x)
  462. if x is None:
  463. raise TypeError(
  464. "positional arguments should all be tensor "
  465. "but args[%d] cannot be recognized as one" % i
  466. )
  467. info = self._tinfo[h]
  468. if x.dtype != info.dtype:
  469. raise TypeError("args[%d].dtype different from last time" % i)
  470. if x.device != info.device:
  471. raise TypeError("args[%d].device different from last time" % i)
  472. info.data_setter.set_value(x._dev_tensor())
  473. self._tensor_remaps[x] = CompiledTensorProxy(h)
  474. kwargs_tensors = {}
  475. for k, x in kwargs.items():
  476. x = find_raw_tensor(x)
  477. if x is not None:
  478. kwargs_tensors[k] = x
  479. if set(kwargs_tensors) != set(self._kwarg_bindings):
  480. too_many = set(kwargs_tensors) - set(self._kwarg_bindings)
  481. too_few = set(self._kwarg_bindings) - set(kwargs_tensors)
  482. if too_many:
  483. raise TraceMismatchError(
  484. "keyword arguments found to be tensor this time "
  485. "but were non-tensor previously: %s" % " ".join(too_many)
  486. )
  487. if too_few:
  488. raise TraceMismatchError(
  489. "keyword arguments found to be non-tensor this time "
  490. "but were tensor previously: %s" % " ".join(too_few)
  491. )
  492. for k, h in self._kwarg_bindings.items():
  493. x = kwargs_tensors[k]
  494. info = self._tinfo[h]
  495. if x.dtype != info.dtype:
  496. raise TypeError("kwargs[%s].dtype different from last time" % k)
  497. if x.device != info.device:
  498. raise TypeError("kwargs[%s].device different from last time" % k)
  499. info.data_setter.set_value(x._dev_tensor())
  500. self._tensor_remaps[x] = CompiledTensorProxy(h)
  501. def _process_outputs(self, outputs):
  502. output_names = None
  503. if isinstance(outputs, collections.Mapping):
  504. output_names, outputs = zip(*sorted(outputs.items()))
  505. elif not isinstance(outputs, collections.Sequence):
  506. outputs = (outputs,)
  507. if not self._untraced:
  508. if output_names != self._output_names:
  509. too_many = set(output_names) - set(self._output_names)
  510. too_few = set(self._output_names) - set(output_names)
  511. if too_many:
  512. raise TraceMismatchError(
  513. "output has more keys than last time: %s" % " ".join(too_many)
  514. )
  515. if too_few:
  516. raise TraceMismatchError(
  517. "output has less keys than last time: %s" % " ".join(too_few)
  518. )
  519. if len(outputs) != len(self._output_bindings):
  520. raise TraceMismatchError("output size differs from last time")
  521. else:
  522. self._output_names = output_names
  523. self._output_bindings = []
  524. for i, x in enumerate(outputs):
  525. x = find_raw_tensor(x)
  526. if x is None:
  527. raise TypeError("every item of return value should be tensor")
  528. if self._untraced:
  529. if not isinstance(x, TraceMixin):
  530. raise RuntimeError("output is not computed from inputs")
  531. h = x._TraceMixin__handle
  532. self._output_bindings.append(h)
  533. else:
  534. if not isinstance(x, CompiledTensorProxy):
  535. raise RuntimeError("output is not computed from inputs")
  536. h = x._CompiledTensorProxy__handle
  537. if h != self._output_bindings[i]:
  538. raise TraceMismatchError(
  539. "retval[%s] is a different tensor than last time"
  540. % (output_names and output_names[i] or i)
  541. )
  542. def get_profile(self):
  543. """
  544. Get profiling result for compiled trace.
  545. :return: a json compatible object.
  546. """
  547. if not self._profiler:
  548. raise RuntimeError("trace is not set with profiling=True")
  549. return json.loads(self._profiler.get())
  550. class CompiledTensorProxy(RawTensor):
  551. """
  552. Duck-typed RawTensor
  553. """
  554. def __init__(self, handle):
  555. self.__handle = handle
  556. self.__info = active_trace._tinfo[handle]
  557. self.__shape = None
  558. self.__data = None
  559. self.__value = None
  560. @property
  561. def dtype(self):
  562. return self.__info.varnode.dtype
  563. @property
  564. def device(self):
  565. return self.__info.varnode.device
  566. @property
  567. def shape(self):
  568. if self.__shape is None:
  569. if self.__info.shape_read:
  570. self.__shape = self.__info.shape_reader.get_value().shape
  571. elif self.__info.data_read:
  572. self.__shape = self._dev_tensor().shape
  573. else:
  574. raise TraceMismatchError("shape of this tensor is not read in trace")
  575. return self.__shape
  576. def numpy(self):
  577. if self.__value is None:
  578. if self.__info.value_read:
  579. self.__value = self.__info.value_reader.get_value()
  580. elif self.__info.data_read:
  581. self.__value = self._dev_tensor().numpy()
  582. else:
  583. raise TraceMismatchError("value of this tensor is not read in trace")
  584. return self.__value
  585. def _dev_tensor(self):
  586. if self.__data is None:
  587. if not self.__info.data_read:
  588. raise TraceMismatchError("raw data of this tensor is not read in trace")
  589. self.__data = self.__info.data_reader.get_value()
  590. return self.__data
  591. def __del__(self):
  592. if self.__info.shape_read and self.__shape is not None:
  593. self.__info.shape_reader.drop_value()
  594. if self.__info.value_read and self.__value is not None:
  595. self.__info.value_reader.drop_value()
  596. if self.__info.data_read and self.__data is not None:
  597. self.__info.data_reader.drop_value()
  598. class LazyEvalTensor(RawTensor):
  599. def __init__(self, varnode):
  600. self.__varnode = varnode
  601. @property
  602. def dtype(self):
  603. return self.__varnode.dtype
  604. @property
  605. def device(self):
  606. return self.__varnode.device
  607. @property
  608. def shape(self):
  609. return self.__varnode.shape
  610. def numpy(self):
  611. return self.__varnode.value
  612. def _dev_tensor(self):
  613. raise RuntimeError("cannot access data during symbolic tracing")
  614. class TraceMixin:
  615. __subclass_cache = {}
  616. def __inject(self, handle):
  617. cache = __class__.__subclass_cache
  618. cls = self.__class__
  619. subcls = cache.get(cls)
  620. if subcls is None:
  621. subcls = cache[cls] = type("Traced" + cls.__name__, (__class__, cls), {})
  622. self.__class__ = subcls
  623. self.__handle = handle
  624. self.__cls = cls
  625. return self
  626. def __restore(self):
  627. cls = self.__cls
  628. del self.__handle
  629. del self.__cls
  630. self.__class__ = cls
  631. return self
  632. @property
  633. def shape(self):
  634. if not skip_tracing:
  635. active_trace._require_shape(self.__handle)
  636. return super().shape
  637. def numpy(self):
  638. if not skip_tracing:
  639. active_trace._require_value(self.__handle)
  640. return super().numpy()
  641. def _dev_tensor(self):
  642. if not skip_tracing:
  643. active_trace._require_data(self.__handle)
  644. return super()._dev_tensor()
  645. class TracedRawTensor(TraceMixin, RawTensor):
  646. pass
  647. class TracedLazyTensor(TraceMixin, LazyEvalTensor):
  648. pass
  649. def assign_raw_tensor(lhs, rhs):
  650. handle = rhs._handle
  651. rhs.__dict__.clear()
  652. lhs.__dict__.clear()
  653. lhs.__class__ = RawTensor
  654. lhs.__init__(handle)
  655. # this hook turns RawTensor into LazyEvalTensor
  656. @apply.register()
  657. def apply_symbolic_mode(op: OpDef, *args: RawTensor):
  658. graph = active_trace._lazy_eval_graph
  659. ivars = [
  660. getattr(x, "_LazyEvalTensor__varnode", None)
  661. or graph.make_const(x._dev_tensor())
  662. for x in args
  663. ]
  664. ovars = apply(op, *ivars)
  665. outputs = [LazyEvalTensor(v) for v in ovars]
  666. active_trace._lazy_eval_tensors.update(outputs)
  667. return outputs
  668. apply.disable(apply_symbolic_mode)
  669. @apply.register()
  670. def apply_const_symbolic_mode(op: Const, *args: RawTensor):
  671. graph = active_trace._lazy_eval_graph
  672. ret = LazyEvalTensor(graph.make_const(op.value, dtype=op.dtype, device=op.device))
  673. active_trace._lazy_eval_tensors.add(ret)
  674. return (ret,)
  675. apply.disable(apply_const_symbolic_mode)
  676. @apply.register()
  677. def apply_compiled_mode(op: OpDef, *args: RawTensor):
  678. if skip_tracing:
  679. args = [
  680. as_raw_tensor(x._dev_tensor()) if x.__class__ is CompiledTensorProxy else x
  681. for x in args
  682. ]
  683. return apply.super(op, *args)
  684. return active_trace._apply_op(op, args)
  685. apply.disable(apply_compiled_mode)
  686. # this hook injects TraceMixin
  687. @apply.register()
  688. def apply_with_tracing(op: OpDef, *args: RawTensor):
  689. outputs = apply.super(op, *args)
  690. active_trace._record_op(op, args, outputs)
  691. return outputs
  692. apply.disable(apply_with_tracing)
  693. @apply.register()
  694. def apply_const_with_tracing(op: Const, *args: RawTensor):
  695. outputs = apply.super(op, *args)
  696. active_trace._record_const(op, outputs)
  697. return outputs
  698. apply.disable(apply_const_with_tracing)
  699. class BrokenRawTensor(RawTensor):
  700. def __getattribute__(self, _):
  701. raise RuntimeError("broken due to misuse of tracing")
  702. def __setattr__(self, *_):
  703. raise RuntimeError("broken due to misuse of tracing")
  704. @functools.singledispatch
  705. def find_raw_tensor(x):
  706. return None
  707. @find_raw_tensor.register(RawTensor)
  708. def _(x):
  709. return x
  710. @find_raw_tensor.register(TensorWrapperBase)
  711. def _(x):
  712. x = getattr(x, "__wrapped__", None)
  713. if x is not None:
  714. return find_raw_tensor(x)
  715. @find_raw_tensor.register(Tensor)
  716. def _(x):
  717. x = getattr(x, "_data", None)
  718. if x is not None:
  719. return find_raw_tensor(x)

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