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

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

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