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

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

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