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

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

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