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

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

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