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

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

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