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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import collections
  10. import contextlib
  11. import functools
  12. import itertools
  13. import json
  14. import os
  15. import pickle
  16. import re
  17. import struct
  18. from typing import Any
  19. import cv2
  20. import numpy as np
  21. from megengine.logger import get_logger
  22. from .. import tensor
  23. from ..core import _imperative_rt as rt
  24. from ..core._imperative_rt import GraphProfiler, GraphProfiler2, SerializationMetadata
  25. from ..core._imperative_rt.core2 import Tensor as RawTensor
  26. from ..core._imperative_rt.core2 import (
  27. TensorWeakRef,
  28. apply,
  29. set_tracing,
  30. skip_tracing,
  31. unset_tracing,
  32. )
  33. from ..core._imperative_rt.ops import (
  34. AssertEqual,
  35. CollectiveComm,
  36. ExternOpr,
  37. RemoteRecv,
  38. RemoteSend,
  39. )
  40. from ..core._trace_option import set_symbolic_shape
  41. from ..core._wrap import as_device
  42. from ..core.ops.builtin import BatchNorm, OpDef
  43. from ..core.tensor import megbrain_graph as G
  44. from ..core.tensor.utils import setscalar
  45. from ..utils import comp_graph_tools as cgtools
  46. from ..utils.naming import AutoNaming
  47. from ..utils.profiler import is_profiling
  48. from .dtr_config import DTRConfig
  49. from .graph_opt_config import GraphOptimizationConfig
  50. from .sublinear_memory_config import SublinearMemoryConfig
  51. logger = get_logger(__name__)
  52. def _input_node_use_static_shape():
  53. return os.environ.get("MEGENGINE_INPUT_NODE_USE_STATIC_SHAPE") is not None
  54. class TraceMismatchError(RuntimeError):
  55. pass
  56. active_trace = None
  57. def is_tracing():
  58. if active_trace is None:
  59. return False
  60. else:
  61. return not skip_tracing
  62. @contextlib.contextmanager
  63. def exclude_from_trace():
  64. global skip_tracing
  65. if skip_tracing or (active_trace is None):
  66. yield
  67. return
  68. try:
  69. skip_tracing = True
  70. unset_tracing()
  71. if active_trace is not None:
  72. active_trace._begin_excluded_region()
  73. yield
  74. finally:
  75. skip_tracing = False
  76. set_tracing()
  77. class TensorInfo:
  78. __slots__ = (
  79. # collected attributes
  80. "name",
  81. "external",
  82. "data_read",
  83. "shape_read",
  84. "value_read",
  85. "exported",
  86. "device",
  87. "dtype",
  88. "shape",
  89. "is_const",
  90. "bound_data",
  91. "bound_data_numpy",
  92. # resources for execution
  93. "varnode",
  94. "data_setter",
  95. "shape_reader",
  96. "value_reader",
  97. "data_reader",
  98. )
  99. def __init__(self):
  100. self.name = None
  101. self.exported = None
  102. self.data_read = None
  103. self.shape_read = None
  104. self.value_read = None
  105. self.bound_data = None
  106. self.bound_data_numpy = None
  107. self.data_setter = None
  108. self.shape_reader = None
  109. self.value_reader = None
  110. self.data_reader = None
  111. def get_numpy(self):
  112. if self.bound_data_numpy is None:
  113. self.bound_data_numpy = self.bound_data.numpy()
  114. return self.bound_data_numpy
  115. _io_op_types = {AssertEqual, CollectiveComm, RemoteSend, RemoteRecv}
  116. class trace:
  117. """Wraps a callable and provide:
  118. * tracing via :meth:`.trace` and :meth:`.dump`
  119. * accelerated evalutaion via :meth:`.__call__`
  120. Args:
  121. function: the function will be traced.
  122. symbolic: whether to apply symbolic execution for tracing. Default: False
  123. capture_as_const: capture global vars or closures as const value. Default: False
  124. record_only: if True, won't run even if call the function. Default: False
  125. sublinear_memory_config: configuration for sublinear memory optimization.
  126. If not None, it enables sublinear memory optimization with given setting.
  127. profiling: whether to profile compiled trace. Default: False
  128. opt_level: optimization level for compiling trace. Default: 2
  129. graph_opt_config: configuration for graph optimization. Default: None
  130. symbolic_shape: whether to use symbolic shape for tracing. Default: True
  131. """
  132. def __new__(cls, *args, **kwargs):
  133. if not args:
  134. return functools.partial(cls, **kwargs)
  135. return super().__new__(cls)
  136. def __init__(
  137. self,
  138. function,
  139. symbolic=False,
  140. capture_as_const=False,
  141. record_only=False,
  142. sublinear_memory_config: SublinearMemoryConfig = None,
  143. dtr_config: DTRConfig = None,
  144. profiling: bool = False,
  145. opt_level: int = 2,
  146. graph_opt_config: GraphOptimizationConfig = None,
  147. symbolic_shape: bool = True,
  148. ):
  149. self.__wrapped__ = function
  150. self._symbolic = symbolic or record_only
  151. self._capture_as_const = capture_as_const or record_only
  152. self._record_only = record_only
  153. self._sublinear_memory_config = sublinear_memory_config
  154. self._dtr_config = dtr_config
  155. self._profiling = profiling
  156. self._profiler = None
  157. self._profiler2 = None
  158. self._graph_opt_level = opt_level
  159. self._graph_opt_config = graph_opt_config
  160. self._symbolic_shape = symbolic_shape
  161. self._output_handles = set()
  162. self._reset()
  163. def _reset(self):
  164. self._untraced = True
  165. self._tinfo = [] # handle -> TensorInfo
  166. self._seq = []
  167. self._pc = 0
  168. self._graph = None
  169. self._need_reset_nodes = None
  170. self._lazy_eval_graph = None
  171. self._lazy_eval_tensors = set()
  172. self._lazy_eval_links = None
  173. self._active_tensors = set()
  174. self._tensor_remaps = None
  175. self._inputs_to_restore = None
  176. self._arg_bindings = None
  177. self._kwarg_bindings = None
  178. self._output_bindings = None
  179. self._output_names = None
  180. def _new_handle(self):
  181. handle = len(self._tinfo)
  182. info = TensorInfo()
  183. self._tinfo.append(info)
  184. return handle, info
  185. def _apply_op(self, op, args):
  186. assert not self._untraced
  187. # check against trace
  188. if self._pc >= len(self._seq):
  189. raise TraceMismatchError("trace should end here, but more op observed")
  190. record = self._seq[self._pc]
  191. op_, ihandles, ohandles = record
  192. if (isinstance(op_, str) and op_ == "Const") or (op != op_):
  193. raise TraceMismatchError("op different from last time")
  194. if len(ihandles) != len(args):
  195. raise TraceMismatchError("op input size different from last time")
  196. # check all inputs of crrent op
  197. for h, x in zip(ihandles, args):
  198. info = self._tinfo[h]
  199. if info.external:
  200. if (
  201. x._compiled_info is not None
  202. and not self._tinfo[x._mixin_handle].exported
  203. ):
  204. raise TraceMismatchError(
  205. "failed to capture: input was an external tensor "
  206. "last time, got an internal tensor this time"
  207. )
  208. if info.bound_data:
  209. if x._compiled_info is not None:
  210. raise TraceMismatchError(
  211. "const capture violated: was an external tensor "
  212. "last time, got an internal tensor this time"
  213. )
  214. if x._handle != info.bound_data._handle:
  215. if not np.array_equal(x.numpy(), info.bound_data.numpy()):
  216. raise TraceMismatchError(
  217. "const capture violated: got "
  218. "a different tensor this time"
  219. )
  220. else:
  221. if info.dtype != x.dtype:
  222. raise TraceMismatchError(
  223. "failed to capture: different dtype from last time"
  224. )
  225. if info.device != x.device:
  226. raise TraceMismatchError(
  227. "failed to capture: different device from last time"
  228. )
  229. info.data_setter.set_value(x._dev_tensor())
  230. else:
  231. if x._mixin_handle == -1:
  232. if x._handle not in self._tensor_remaps:
  233. raise TraceMismatchError(
  234. "unexpected capture: trying to use an external tensor as "
  235. "input, but that input was an internal tensor last time"
  236. )
  237. else:
  238. x._mixin_handle = self._tensor_remaps[
  239. x._handle
  240. ]._CompiledTensorProxy__handle
  241. if x._mixin_handle != h:
  242. raise TraceMismatchError(
  243. "mis-wiring: input edge to an data flow "
  244. "graph node is different from last time"
  245. )
  246. self._pc += 1
  247. outputs = []
  248. for h in ohandles:
  249. info = self._tinfo[h]
  250. # generate output tensor and create compied info
  251. y = RawTensor(info.varnode)
  252. y._compiled_info = CompiledTensorProxy(h)
  253. y._mixin_handle = h
  254. outputs += [y]
  255. self._active_tensors.add(TensorWeakRef(y))
  256. self._output_handles.update(ohandles)
  257. return outputs
  258. def _apply_const(self, value, dtype, device):
  259. assert not self._untraced
  260. # check against trace
  261. if self._pc >= len(self._seq):
  262. raise TraceMismatchError("trace should end here, but more op observed")
  263. record = self._seq[self._pc]
  264. op_, ihandles, ohandles = record
  265. # Const op is represented by a str
  266. assert isinstance(op_, str) and op_ == "Const"
  267. expected = self._tinfo[ohandles[0]].get_numpy()
  268. shape = value.shape
  269. if shape != expected.shape or dtype != expected.dtype:
  270. eq = False
  271. elif shape == ():
  272. eq = expected.item() == value.item()
  273. elif shape == (1,):
  274. eq = expected[0] == value[0]
  275. else:
  276. eq = np.all(value == expected)
  277. if not eq:
  278. raise TraceMismatchError(
  279. "const tensor violated: got a different tensor this time"
  280. )
  281. self._pc += 1
  282. (h,) = ohandles
  283. outputs = [self._tinfo[h].bound_data]
  284. return outputs
  285. # run in first step, record information for trace
  286. def _record_op(self, op, inputs, outputs):
  287. if skip_tracing:
  288. for x in inputs:
  289. h = getattr(x, "_mixin_handle", -1)
  290. if h >= 0:
  291. self._tinfo[h].data = True
  292. return
  293. ihandles = []
  294. for x in inputs:
  295. h = getattr(x, "_mixin_handle", -1)
  296. if h < 0 or (not self._capture_as_const and self._tinfo[h].exported):
  297. h, info = self._new_handle()
  298. name = AutoNaming.gen_name(x)
  299. info.name = name
  300. info.external = True
  301. info.device = x.device
  302. info.dtype = x.dtype
  303. info.shape = x.shape
  304. if self._capture_as_const:
  305. info.bound_data = RawTensor(
  306. x.numpy(), x.dtype, x.device, False, name
  307. )
  308. ihandles.append(h)
  309. ohandles = []
  310. for x in outputs:
  311. h, info = self._new_handle()
  312. ohandles.append(h)
  313. info.external = False
  314. x._mixin_handle = h
  315. x._recording = True
  316. x._trace_mixin_info = info
  317. self._active_tensors.add(TensorWeakRef(x))
  318. if self._symbolic:
  319. self._lazy_eval_tensors.add(TensorWeakRef(x))
  320. self._seq.append((op, tuple(ihandles), tuple(ohandles)))
  321. def _record_const(self, outputs):
  322. if skip_tracing:
  323. (x,) = outputs
  324. h = getattr(x, "_mixin_handle", -1)
  325. if h >= 0:
  326. self._tinfo[h].data_read = True
  327. return
  328. (x,) = outputs
  329. h, info = self._new_handle()
  330. ohandles = [h]
  331. info.external = True
  332. info.device = x.device
  333. info.dtype = x.dtype
  334. info.shape = x.shape
  335. info.bound_data = x
  336. info.bound_data_numpy = None
  337. info.is_const = True
  338. x._mixin_handle = h
  339. x._recording = True
  340. x._trace_mixin_info = info
  341. if self._symbolic:
  342. self._lazy_eval_tensors.add(TensorWeakRef(x))
  343. self._seq.append(("Const", tuple(), tuple(ohandles)))
  344. def _set_active(self, active: bool):
  345. global active_trace
  346. if active:
  347. if active_trace:
  348. raise NotImplementedError("sorry, not implemented: nested trace")
  349. active_trace = self
  350. else:
  351. assert active_trace is self
  352. active_trace = None
  353. def _init_trace(self, symbolic: bool):
  354. if symbolic:
  355. self._lazy_eval_graph = G.Graph()
  356. self._apply_graph_options(self._lazy_eval_graph)
  357. self._lazy_eval_links = ()
  358. def _take_escaped_tensors(self):
  359. escaped_tensors = tuple(filter(lambda x: x() is not None, self._active_tensors))
  360. self._active_tensors.clear()
  361. return escaped_tensors
  362. def _lazy_eval(self, lazy_eval_graph, lazy_eval_tensors, lazy_eval_links):
  363. lazy_eval_tensors = [x() for x in lazy_eval_tensors]
  364. lazy_eval_tensors = [x for x in lazy_eval_tensors if x is not None]
  365. readers = [G.OutputNode(x._varnode).outputs[0] for x in lazy_eval_tensors]
  366. self._apply_graph_options(lazy_eval_graph)
  367. lazy_eval_graph.options.graph_opt_level = self._graph_opt_level
  368. lazy_eval_graph._set_priority_to_id([*lazy_eval_links, *readers])
  369. lazy_eval_graph.compile(*lazy_eval_links, *readers)
  370. self._execute_graph(lazy_eval_graph)
  371. lazy_eval_graph.wait()
  372. for r, x in zip(readers, lazy_eval_tensors):
  373. # get values from lazy_eval_graph and assign to lazy_eval tensor
  374. x._handle = RawTensor(r.op.get_value())._handle
  375. x._reset_varnode()
  376. @contextlib.contextmanager
  377. def _setup(self):
  378. interrupted = False
  379. def do_enter():
  380. set_tracing()
  381. self._save_symbolic_shape = set_symbolic_shape(self._symbolic_shape)
  382. self._set_active(True)
  383. if self._untraced:
  384. self._init_trace(self._symbolic)
  385. else:
  386. if self._graph is None:
  387. self._compile()
  388. self._execute_graph(self._graph)
  389. def do_finalize():
  390. escaped_tensors = self._take_escaped_tensors()
  391. if self._untraced:
  392. if self._record_only:
  393. self._lazy_eval_graph = None
  394. self._lazy_eval_tensors = None
  395. self._lazy_eval_links = None
  396. else:
  397. for x in escaped_tensors:
  398. if x():
  399. info = self._tinfo[x()._mixin_handle]
  400. info.data_read = True
  401. x()._mixin_handle = -1
  402. x()._recording = False
  403. if self._inputs_to_restore:
  404. for x in self._inputs_to_restore:
  405. x._mixin_handle = -1
  406. x._recording = False
  407. if self._symbolic and (
  408. self._lazy_eval_tensors or self._lazy_eval_links
  409. ):
  410. # eval lazy eval tensors
  411. self._lazy_eval(
  412. self._lazy_eval_graph,
  413. self._lazy_eval_tensors,
  414. self._lazy_eval_links,
  415. )
  416. self._lazy_eval_graph = None
  417. self._lazy_eval_tensors = None
  418. self._lazy_eval_links = None
  419. self._untraced = False
  420. else:
  421. # compiled_tensor leaks
  422. if self._pc == len(self._seq):
  423. for x in escaped_tensors:
  424. try:
  425. x().__init__(RawTensor(x()._dev_tensor()))
  426. except RuntimeError:
  427. # TraceMismatchError thrown in do_exit
  428. pass
  429. self._graph.wait()
  430. self._reset_exec_env()
  431. # reset status
  432. self._pc = 0
  433. self._tensor_remaps = None
  434. self._set_active(False)
  435. set_symbolic_shape(self._save_symbolic_shape)
  436. unset_tracing()
  437. def do_exit():
  438. unset_tracing()
  439. if not self._untraced and self._pc != len(self._seq):
  440. raise TraceMismatchError("premature end")
  441. if not self._symbolic or not self._untraced:
  442. # reset output tensors
  443. for x in self._active_tensors.copy():
  444. strong_x = x()
  445. if strong_x is not None:
  446. strong_x._dev_tensor()
  447. strong_x._reset_varnode()
  448. strong_x._mixin_handle = -1
  449. strong_x._recording = False
  450. strong_x._trace_mixin_info = None
  451. try:
  452. do_enter()
  453. yield
  454. do_exit()
  455. except:
  456. interrupted = True
  457. raise
  458. finally:
  459. do_finalize()
  460. if interrupted:
  461. self._reset()
  462. def _begin_excluded_region(self):
  463. if self._capture_as_const:
  464. raise RuntimeError(
  465. "exclude_from_trace cannot be used with capture_as_const"
  466. )
  467. if self._untraced:
  468. # conditionally reading a compiled tensor in excluded region
  469. # is permitted, so we have to assume every tensor might be read
  470. for x in self._active_tensors:
  471. strong_x = x()
  472. if strong_x:
  473. info = self._tinfo[strong_x._mixin_handle]
  474. info.exported = True
  475. info.data_read = True
  476. else:
  477. for x in self._active_tensors:
  478. strong_x = x()
  479. if strong_x:
  480. strong_x._dev_tensor()
  481. def _apply_graph_options(self, graph):
  482. graph.options.no_force_inplace = True
  483. graph.options.seq_opt.enable_seq_comp_node_opt = False
  484. graph.options.graph_opt_level = self._graph_opt_level
  485. if self._dtr_config is not None:
  486. graph.options.enable_dtr_memory_opt = True
  487. graph.options.dtr_config.eviction_threshold = (
  488. self._dtr_config.eviction_threshold
  489. )
  490. graph.options.dtr_config.evictee_minimum_size = (
  491. self._dtr_config.evictee_minimum_size
  492. )
  493. graph.options.dtr_config.recomp_memory_factor = (
  494. self._dtr_config.recomp_memory_factor
  495. )
  496. graph.options.dtr_config.recomp_time_factor = (
  497. self._dtr_config.recomp_time_factor
  498. )
  499. # graph optimization
  500. if self._graph_opt_config is not None:
  501. mapping = {None: 0, False: 1, True: 2}
  502. jit_config = graph.options.graph_opt.jit_config
  503. jit_config.fuse_dimshuffle = mapping[
  504. self._graph_opt_config.jit_fuse_dimshuffle
  505. ]
  506. jit_config.fuse_reduce = mapping[self._graph_opt_config.jit_fuse_reduce]
  507. # sublinear
  508. if self._sublinear_memory_config is not None:
  509. graph.options.enable_sublinear_memory_opt = True
  510. sublinear_config = graph.options.sublinear_mem_config
  511. sublinear_config.lb_memory_mb = self._sublinear_memory_config.lb_memory_mb
  512. sublinear_config.genetic_nr_iter = (
  513. self._sublinear_memory_config.genetic_nr_iter
  514. )
  515. sublinear_config.genetic_pool_size = (
  516. self._sublinear_memory_config.genetic_pool_size
  517. )
  518. sublinear_config.thresh_nr_try = self._sublinear_memory_config.thresh_nr_try
  519. sublinear_config.num_worker = self._sublinear_memory_config.num_worker
  520. # profile
  521. if self._profiling:
  522. self._profiler = GraphProfiler(graph)
  523. self._profiler2 = None
  524. if int(os.getenv("MEGENGINE_INPLACE_UPDATE", "0")):
  525. graph.options.var_sanity_check_first_run = False
  526. def _execute_graph(self, graph: G.Graph, *args):
  527. if is_profiling() and (self._profiler2 is None):
  528. self._profiler2 = GraphProfiler2(graph)
  529. elif not is_profiling() and (self._profiler2 is not None):
  530. self._profiler2 = None
  531. graph.execute(*args)
  532. def _compile(self):
  533. graph = self._graph = G.Graph()
  534. graph.options.async_exec_level = 0b100
  535. self._apply_graph_options(graph)
  536. need_reset_nodes = self._need_reset_nodes = []
  537. # links enforce ordering of I/O nodes
  538. in_out_links = ()
  539. io_links = ()
  540. readers = []
  541. if self._capture_as_const:
  542. for h in itertools.chain(self._arg_bindings, self._kwarg_bindings.values()):
  543. info = self._tinfo[h]
  544. opnode = info.data_setter = G.InputNode(
  545. device=info.device,
  546. dtype=info.dtype,
  547. shape=info.shape or (1,),
  548. graph=graph,
  549. use_static_shape=_input_node_use_static_shape(),
  550. )
  551. need_reset_nodes.append(opnode)
  552. info.varnode = opnode.outputs[0]
  553. in_out_links += opnode.outputs[1:]
  554. for op, ihandles, ohandles in self._seq:
  555. if isinstance(op, str) and op == "Const":
  556. assert len(ihandles) == 0
  557. (h,) = ohandles
  558. info = self._tinfo[h]
  559. if not hasattr(info, "varnode"):
  560. assert info.external
  561. assert info.bound_data
  562. info.varnode = graph.make_const(
  563. info.get_numpy(), info.bound_data.dtype, info.bound_data.device,
  564. )
  565. continue
  566. require_links = type(op) in _io_op_types
  567. ivars = []
  568. for i, h in enumerate(ihandles):
  569. info = self._tinfo[h]
  570. if not hasattr(info, "varnode"):
  571. assert info.external
  572. if info.bound_data:
  573. if getattr(info, "is_const", False):
  574. info.varnode = graph.make_const(
  575. info.get_numpy(),
  576. info.bound_data.dtype,
  577. info.bound_data.device,
  578. )
  579. else:
  580. info.varnode = graph.make_const(
  581. info.bound_data._dev_tensor()
  582. # info.bound_data.numpy()
  583. )
  584. else:
  585. opnode = info.data_setter = G.InputNode(
  586. *in_out_links,
  587. device=info.device,
  588. dtype=info.dtype,
  589. shape=info.shape or (1,),
  590. graph=graph,
  591. use_static_shape=_input_node_use_static_shape(),
  592. )
  593. need_reset_nodes.append(opnode)
  594. info.varnode, *in_out_links = opnode.outputs
  595. if require_links and i == 0 and len(io_links) > 0:
  596. opnode = G.VirtualDepNode(
  597. [info.varnode, *io_links], str(io_links[0].device)
  598. )
  599. info.varnode = opnode.outputs[0]
  600. io_links = (info.varnode,)
  601. ivars.append(info.varnode)
  602. ovars = G.apply_normal_varnode(op, *ivars)
  603. if require_links and len(ovars) > 0:
  604. io_links = (ovars[0],)
  605. assert len(ovars) == len(ohandles)
  606. for h, v in zip(ohandles, ovars):
  607. info = self._tinfo[h]
  608. info.varnode = v
  609. def add_reader(opnode):
  610. nonlocal in_out_links
  611. need_reset_nodes.append(opnode)
  612. readers.append(opnode.outputs[0])
  613. in_out_links = opnode.outputs
  614. if info.data_read:
  615. # Shape can be obtained from data so doesn't need its own
  616. # output node. On the other hand, value is read separately
  617. # to leverage eager h2d copy
  618. info.shape_read = False
  619. opnode = info.data_reader = G.OutputNode(v, *in_out_links)
  620. add_reader(opnode)
  621. if info.value_read:
  622. opnode = info.value_reader = G.ValueOutputNode(v, *in_out_links)
  623. add_reader(opnode)
  624. if info.shape_read:
  625. opnode = info.shape_reader = G.AttrOutputNode(v, *in_out_links)
  626. add_reader(opnode)
  627. graph.options.graph_opt_level = self._graph_opt_level
  628. graph._set_priority_to_id([*readers, *in_out_links, *io_links])
  629. graph.compile(*readers, *in_out_links, *io_links)
  630. def _reset_exec_env(self):
  631. for opnode in self._need_reset_nodes:
  632. opnode.reset()
  633. def __call__(self, *args, **kwargs):
  634. with self._setup():
  635. if self._capture_as_const:
  636. self._process_inputs(*args, **kwargs)
  637. outputs = self.__wrapped__(*args, **kwargs)
  638. if self._capture_as_const:
  639. self._process_outputs(outputs)
  640. return outputs
  641. def _make_feed(
  642. self,
  643. graph,
  644. outputs,
  645. input_data,
  646. repeat,
  647. silent,
  648. no_assert,
  649. maxerr,
  650. resize_input,
  651. input_transform,
  652. ):
  653. def auto_reformat_image(path, data, dst_shape):
  654. """reformat image to target shape
  655. :param data: image data as numpy array
  656. :param dst_shape: target shape
  657. """
  658. dim3_format = False # required input format does not contain batch
  659. hwc_format = False # required input format is NHWC
  660. if not dst_shape: # input tensor shape is not predefined
  661. if len(data.shape) == 2:
  662. chl = 1
  663. h = data.shape[0]
  664. w = data.shape[1]
  665. else:
  666. assert (
  667. len(data.shape) == 3
  668. ), "Input image must be of dimension 2 or 3"
  669. h, w, chl = data.shape
  670. dst_shape = (1, chl, h, w)
  671. if len(dst_shape) == 3:
  672. dst_shape = (1,) + dst_shape
  673. dim3_format = True
  674. assert len(dst_shape) == 4, "bad dst_shape: {}".format(dst_shape)
  675. chl = dst_shape[1]
  676. if chl in [1, 3]:
  677. n, c, h, w = dst_shape
  678. dst_shape = (n, h, w, c)
  679. else:
  680. chl = dst_shape[3]
  681. assert chl in [
  682. 1,
  683. 3,
  684. ], "can not infer input format from shape: {}".format(dst_shape)
  685. hwc_format = True
  686. # dst_shape has now been normalized to NHWC format
  687. if resize_input:
  688. h, w = dst_shape[1:3]
  689. data = cv2.resize(data, (w, h))
  690. logger.info("input {} resized to {}".format(path, data.shape))
  691. if chl == 1:
  692. data = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)
  693. data = data[:, :, np.newaxis]
  694. assert data.ndim == 3
  695. data = data[np.newaxis]
  696. # data normalized to NHWC format
  697. if not hwc_format:
  698. data = np.transpose(data, (0, 3, 1, 2))
  699. if dim3_format:
  700. data = np.squeeze(data, 0)
  701. return data
  702. def read_input_data(dst_shape, dtype, path):
  703. def check_shape_equal(dst_shape, data_shape):
  704. if len(dst_shape):
  705. assert len(data_shape) == len(
  706. dst_shape
  707. ), "input/data shapes mismatch: {} vs {}".format(
  708. dst_shape, data_shape
  709. )
  710. if data_shape[1:] != dst_shape[1:]:
  711. logger.warning(
  712. "dst_shape is {}; data_shape is {}".format(
  713. dst_shape, data_shape
  714. )
  715. )
  716. if path.startswith("#"):
  717. assert not resize_input
  718. assert not input_transform
  719. spec = path
  720. m = re.match(
  721. r"^#rand\(([-0-9.]*)\s*,\s*([-0-9.]*)\s*(,[^\)]+)?\)$", spec
  722. )
  723. assert m, "bad spec {}".format(spec)
  724. rng_min = float(m.group(1))
  725. rng_max = float(m.group(2))
  726. if m.group(3):
  727. shape_str = m.group(3)
  728. try:
  729. shape = shape_str[1:].split(",")
  730. if shape[-1].strip() == "...":
  731. shape = shape[:-1]
  732. shape.extend(list(dst_shape[len(shape) :]))
  733. data_shape = tuple(map(int, shape))
  734. except ValueError as e:
  735. raise ValueError("bad spec {}: {}".format(spec, e.args))
  736. else:
  737. data_shape = dst_shape
  738. check_shape_equal(dst_shape, data_shape)
  739. return np.random.uniform(rng_min, rng_max, data_shape).astype(dtype)
  740. # try to load image
  741. data = cv2.imread(path, cv2.IMREAD_COLOR)
  742. if data is None:
  743. assert not resize_input
  744. data = np.load(path)
  745. assert isinstance(data, np.ndarray)
  746. else:
  747. # load image succeeds, so we expect input format is image format
  748. data = auto_reformat_image(path, data, dst_shape)
  749. data = np.repeat(data, repeat, axis=0)
  750. if repeat > 1:
  751. logger.info(
  752. "repeat input for {} times, data shape is {}".format(
  753. repeat, data.shape
  754. )
  755. )
  756. check_shape_equal(dst_shape, data.shape)
  757. if input_transform:
  758. data = eval(input_transform, {"data": data, "np": np})
  759. return data
  760. def gen_one_testcase(inputs, spec):
  761. paths = spec.split(";")
  762. if len(paths) != len(inputs):
  763. if len(paths) == 1 and paths[0].startswith("#"):
  764. paths = ["{}:{}".format(name, paths[0]) for name in inputs.keys()]
  765. assert len(paths) == len(
  766. inputs
  767. ), "required inputs: {}; data paths: {}".format(inputs.keys(), paths)
  768. if len(paths) == 1 and ":" not in paths[0]:
  769. paths[0] = next(iter(inputs.keys())) + ":" + paths[0]
  770. ret = {}
  771. for path in paths:
  772. var, path = path.split(":")
  773. ret[var] = read_input_data(inputs[var].shape, inputs[var].dtype, path)
  774. return ret
  775. inputs = cgtools.get_dep_vars(outputs, "Host2DeviceCopy")
  776. inputs = {i.name: i for i in inputs}
  777. if not no_assert:
  778. replace_varmap = {}
  779. inp_map = {}
  780. # replace var use InputNode
  781. for name, var in inputs.items():
  782. inp = G.InputNode(
  783. device="xpux", dtype=var.dtype, shape=var.shape, graph=graph
  784. )
  785. replace_varmap[var] = inp.outputs[0]._node
  786. inp_map[name] = inp
  787. new = cgtools.replace_vars(outputs, replace_varmap)
  788. if isinstance(new, rt.VarNode):
  789. new = list(new)
  790. output_nodes = [G.OutputNode(var) for var in new]
  791. func = graph.compile(*[node.outputs[0]._node for node in output_nodes])
  792. def make_dev_tensor(value, dtype=None, device=None):
  793. return tensor(value, dtype=dtype, device=device)._dev_tensor()
  794. def calculate(*args, **kwargs):
  795. output_val = []
  796. # set inputs value
  797. for name, var in inputs.items():
  798. val = kwargs.pop(name, None)
  799. assert val is not None, "miss input name{}".format(name)
  800. dev_tensor = make_dev_tensor(val, dtype=var.dtype, device="xpux")
  801. inp_map[name].set_value(dev_tensor)
  802. func.execute()
  803. for res in output_nodes:
  804. output_val.append(res.get_value().numpy())
  805. return output_val
  806. def expect_name(var):
  807. return "{}:expect".format(var.name)
  808. testcases = []
  809. np.set_printoptions(precision=2, threshold=4, suppress=True)
  810. data_list = []
  811. for item in input_data:
  812. if item.startswith("@"):
  813. with open(item[1:], "r") as f:
  814. data_list.extend(
  815. [line.rstrip() for line in f if line.rstrip() != ""]
  816. )
  817. else:
  818. data_list.append(item)
  819. for inp_spec in data_list:
  820. cur_testcase = gen_one_testcase(inputs, inp_spec)
  821. assert len(cur_testcase) == len(
  822. inputs
  823. ), "required inputs: {}; given data: {}".format(
  824. inputs.keys(), cur_testcase.keys()
  825. )
  826. if not no_assert:
  827. outputs_get = calculate(**cur_testcase)
  828. for var, val in zip(outputs, outputs_get):
  829. cur_testcase[expect_name(var)] = val
  830. logger.info(
  831. "generate test groundtruth: var={} shape={} range=({}, {})"
  832. " mean={} var={}".format(
  833. var,
  834. val.shape,
  835. val.min(),
  836. val.max(),
  837. np.mean(val),
  838. np.var(val),
  839. )
  840. )
  841. testcases.append(cur_testcase)
  842. logger.info(
  843. "add testcase: \n {}".format(
  844. "\n ".join(
  845. "{}: shape={} dtype={} range=({:.2f},{:.2f}) "
  846. "mean={:.2f} sd={:.2f}".format(
  847. k, v.shape, v.dtype, v.min(), v.max(), np.mean(v), np.std(v)
  848. )
  849. for k, v in sorted(cur_testcase.items())
  850. )
  851. )
  852. )
  853. if not no_assert:
  854. def expect_shp(var):
  855. ret = var.shape
  856. if ret:
  857. return ret
  858. return testcases[0][expect_name(var)].shape
  859. def assert_equal(expect, real, **kwargs):
  860. op = AssertEqual(**kwargs)
  861. (res,) = G.apply_normal_varnode(op, expect, real)
  862. return res._node
  863. verbose = not silent
  864. outputs_new = []
  865. for i in outputs:
  866. device = rt.CompNode("xpux")
  867. dtype = i.dtype
  868. name = expect_name(i)
  869. shape = expect_shp(i)
  870. # make expect output as one input of model.
  871. expect_get = rt.make_h2d(graph, device, dtype, shape, name)
  872. # insert assert opr to check expect and real.
  873. outputs_new.append(
  874. assert_equal(expect_get, i, verbose=verbose, maxerr=maxerr,)
  875. )
  876. inputs[expect_name(i)] = expect_get
  877. outputs = outputs_new
  878. return {"outputs": outputs, "testcases": testcases}
  879. def dump(
  880. self,
  881. file,
  882. *,
  883. arg_names=None,
  884. output_names=None,
  885. append=False,
  886. keep_var_name: int = 1,
  887. keep_opr_name: bool = False,
  888. keep_param_name: bool = False,
  889. keep_opr_priority: bool = False,
  890. strip_info_file=None,
  891. append_json=False,
  892. optimize_for_inference=True,
  893. user_info: Any = None,
  894. enable_metadata: bool = True,
  895. input_data=None,
  896. repeat=1,
  897. silent=False,
  898. no_assert=False,
  899. maxerr=1e-4,
  900. resize_input=False,
  901. input_transform=None,
  902. dump_format: str = None,
  903. **kwargs
  904. ):
  905. r"""Serializes trace to file system.
  906. Args:
  907. file: output file, could be file object or filename.
  908. arg_names: names of the input tensors in the traced function.
  909. output_names: names of the output tensors in the traced function,
  910. use the default name if not specified.
  911. append: whether output is appended to ``file``.
  912. Only works when ``file`` is str.
  913. keep_var_name: level for keeping variable names:
  914. * 0: none of the names are kept
  915. * 1: (default)keep names of output vars
  916. * 2: keep names of all (output and internal) vars
  917. keep_opr_name: whether to keep operator names.
  918. keep_param_name: whether to keep param names, so param values can be
  919. easily manipulated after loading model
  920. keep_opr_priority: whether to keep priority setting for operators
  921. strip_info_file: a string for path or a file handler. if is not None,
  922. then the dump information for code strip would be written to ``strip_info_file``
  923. append_json: will be check when `strip_info_file` is not None. if set
  924. true, the information for code strip will be append to strip_info_file.
  925. if set false, will rewrite strip_info_file
  926. optimize_for_inference: enbale optmizations,
  927. will skip all optimize options if this is False. Default: True
  928. user_info: any type object, which will be pickled to bytes.
  929. enable_metadata: whether to save metadata into output file.
  930. input_data: input test data and current network output would be used as groundtruth.
  931. The format is "var0:file0;var1:file1..." to specify data files for input vars.
  932. It can also be "#rand(min,max,shape...)" for generating random input data, for
  933. example, "#rand(0,255)", "#rand(0,255,1,3,224,224)" or "#rand(0, 255, 1, ...)"
  934. where `...` means the remaining part of the original shape. If the shape is not
  935. specified, the shape of corresponding input tensors in the network will be used.
  936. If there is only one input var, its name can be omitted. Each data file can either
  937. be an image which can be loaded by opencv, or a pickled numpy.ndarray. This option
  938. can be given multiple times to add multiple testcases. If you start the data
  939. with the letter @, the rest should be a filename, and each line in the file should
  940. be a single datum in the format described above. *NOTE* If `input_data` is not None,
  941. you can only use load-and-run to run the output file.
  942. repeat: how many times the input image is repeated. Useful when running benchmark for
  943. batch size other than one. Have no effect on randomly generated input data.
  944. silent: whether set verbose to False in assert_equal opr.
  945. no_assert: whether insert assert_equal opr to check result; this option is useful for
  946. benchmarking.
  947. maxerr: max error for assert_equal check during runtime.
  948. resize_input: whether resize input image to fit input var shape.
  949. input_transform: a python expression to transform the input data.
  950. Example: data / np.std(data)
  951. dump_format: using different dump formats. the open source MegEngine defaults to the FBS
  952. format. internal MegEngine have a choice of FBS and internal proprietary formats
  953. Keyword Arguments:
  954. * enable_io16xc32 --
  955. whether to use float16 for I/O between oprs and use
  956. float32 as internal computation precision. Note the output var would be
  957. changed to float16.
  958. * enable_ioc16 --
  959. whether to use float16 for both I/O and computation
  960. precision.
  961. * enable_hwcd4 --
  962. whether to use NHWCD4 data layout. This is faster on some
  963. OpenCL backend.
  964. * enable_nchw88 --
  965. whether to use NCHW88 data layout, currently
  966. used in X86 AVX backend.
  967. * enable_nchw44 --
  968. whether to use NCHW44 data layout, currently
  969. used in arm backend.
  970. * enable_nchw44_dot --
  971. whether to use NCHW44_dot data layout, currently
  972. used in armv8.2+dotprod backend.
  973. * enable_nchw4 --
  974. whether to use NCHW4 data layout, currently
  975. used in nvidia backend(based on cudnn).
  976. * enable_nchw32 --
  977. whether to use NCHW32 data layout, currently
  978. used in nvidia backend with tensorcore(based on cudnn).
  979. * enable_chwn4 --
  980. whether to use CHWN4 data layout, currently
  981. used in nvidia backend with tensorcore.
  982. * enable_nchw64 --
  983. whether to use NCHW64 data layout, used for fast int4
  984. support on Nvidia GPU.
  985. * enable_fuse_conv_bias_nonlinearity: whether to fuse conv+bias+nonlinearty
  986. into one opr.
  987. * enable_fuse_conv_bias_with_z: whether to fuse conv_bias with z
  988. input for inference on nvidia backend(this optimization pass will
  989. result in mismatch of the precision of output of training and
  990. inference)
  991. * enable_fuse_preprocess: whether to fuse astype\pad_channel\dimshuffle and
  992. etc opr
  993. """
  994. if not self._capture_as_const:
  995. raise ValueError(
  996. "you must specify capture_as_const=True at __init__ to use dump"
  997. )
  998. if self._untraced and len(self._seq) == 0:
  999. raise RuntimeError("should do record first before dump")
  1000. if self._output_names and output_names:
  1001. raise TypeError(
  1002. "cannot specify output_names when output is already in dict format"
  1003. )
  1004. if output_names and not isinstance(output_names, collections.abc.Sequence):
  1005. output_names = (output_names,)
  1006. if output_names and len(output_names) != len(self._output_bindings):
  1007. raise ValueError(
  1008. "wrong number of output_names, should be {} values".format(
  1009. len(self._output_bindings)
  1010. )
  1011. )
  1012. without_arg_names = arg_names is None
  1013. if without_arg_names:
  1014. arg_names = ["arg_%d" % i for i in range(len(self._arg_bindings))]
  1015. if arg_names and not isinstance(arg_names, collections.abc.Sequence):
  1016. arg_names = (arg_names,)
  1017. if arg_names and len(arg_names) != len(self._arg_bindings):
  1018. raise ValueError(
  1019. "wrong number of arg_names, should be {} values".format(
  1020. len(self._arg_bindings)
  1021. )
  1022. )
  1023. output_names = output_names or self._output_names
  1024. def dumped_device(info):
  1025. device_name = info.device.logical_name
  1026. if device_name[:3] in ("cpu", "gpu", "xpu"):
  1027. return as_device("xpux")
  1028. return info.device
  1029. h2v = {}
  1030. graph = G.Graph()
  1031. # apply graph_opt_level in dump
  1032. if self._graph_opt_level is not None:
  1033. graph.options.graph_opt_level = self._graph_opt_level
  1034. for i, h in enumerate(self._arg_bindings):
  1035. info = self._tinfo[h]
  1036. h2v[h] = graph.make_h2d(
  1037. dtype=info.dtype,
  1038. device=dumped_device(info),
  1039. shape=info.shape or (1,),
  1040. name=info.name if without_arg_names and info.name else arg_names[i],
  1041. )
  1042. for k, h in self._kwarg_bindings.items():
  1043. info = self._tinfo[h]
  1044. h2v[h] = graph.make_h2d(
  1045. dtype=info.dtype,
  1046. device=dumped_device(info),
  1047. shape=info.shape or (1,),
  1048. name=k,
  1049. )
  1050. for op, ihandles, ohandles in self._seq:
  1051. if isinstance(op, str) and op == "Const":
  1052. assert len(ihandles) == 0
  1053. (h,) = ohandles
  1054. info = self._tinfo[h]
  1055. if h not in h2v:
  1056. assert info.external
  1057. assert info.bound_data
  1058. h2v[h] = graph.make_const(
  1059. info.get_numpy(),
  1060. dtype=info.dtype,
  1061. device=dumped_device(info),
  1062. name=info.name,
  1063. )
  1064. continue
  1065. ivars = []
  1066. for h in ihandles:
  1067. info = self._tinfo[h]
  1068. if h not in h2v:
  1069. assert info.external
  1070. assert info.bound_data
  1071. h2v[h] = graph.make_const(
  1072. info.get_numpy(),
  1073. dtype=info.dtype,
  1074. device=dumped_device(info),
  1075. name=info.name,
  1076. )
  1077. ivars.append(h2v[h])
  1078. if isinstance(op, BatchNorm):
  1079. assert (
  1080. op.fwd_mode == BatchNorm.FwdMode.INFERENCE
  1081. ), "can not dump BatchNorm in training mode, maybe you forget to do model.eval()?"
  1082. ovars = G.apply_normal_varnode(op, *ivars)
  1083. AutoNaming.record_opnode(ovars[0].op)
  1084. assert len(ovars) == len(ohandles)
  1085. h2v.update(zip(ohandles, ovars))
  1086. for i in ohandles:
  1087. name = AutoNaming.get_var_name(i)
  1088. if name is not None:
  1089. h2v[i].name = name
  1090. AutoNaming.remove_duplicate_names()
  1091. dest_vars = []
  1092. for i, h in enumerate(self._output_bindings):
  1093. v = h2v[h]
  1094. if output_names:
  1095. v.name = output_names[i]
  1096. dest_vars.append(v)
  1097. dest_vars = [i._node for i in dest_vars]
  1098. if input_data is not None:
  1099. feeds = self._make_feed(
  1100. graph,
  1101. dest_vars,
  1102. input_data,
  1103. repeat,
  1104. silent,
  1105. no_assert,
  1106. maxerr,
  1107. resize_input,
  1108. input_transform,
  1109. )
  1110. assert (
  1111. isinstance(feeds, dict) and feeds["testcases"]
  1112. ), "testcases can not be empty"
  1113. dest_vars = feeds["outputs"]
  1114. if optimize_for_inference:
  1115. dest_vars, optimize_options = G.optimize_for_inference(dest_vars, **kwargs)
  1116. dest_vars = [i._node for i in dest_vars]
  1117. metadata = SerializationMetadata()
  1118. if enable_metadata:
  1119. metadata.user_info = pickle.dumps(user_info)
  1120. metadata.is_valid = True
  1121. metadata.graph_modified = False
  1122. if optimize_for_inference:
  1123. metadata.optimize_options = optimize_options
  1124. if isinstance(file, str):
  1125. permission = "wb" if append == False else "ab"
  1126. file = open(file, permission)
  1127. if keep_opr_priority:
  1128. graph._set_priority_to_id(dest_vars)
  1129. if input_data is not None:
  1130. file.write(b"mgbtest0")
  1131. file.write(struct.pack("I", len(feeds["testcases"])))
  1132. dump_content, dump_info = G.dump_graph(
  1133. dest_vars,
  1134. keep_var_name=keep_var_name,
  1135. keep_opr_name=keep_opr_name,
  1136. keep_param_name=keep_param_name,
  1137. keep_opr_priority=keep_opr_priority,
  1138. strip_info_file=strip_info_file,
  1139. append_json=append_json,
  1140. metadata=metadata,
  1141. dump_format=dump_format,
  1142. )
  1143. file.write(dump_content)
  1144. if input_data is not None:
  1145. inputs = cgtools.get_dep_vars(dest_vars, "Host2DeviceCopy")
  1146. inputs = sorted((i.name, i.dtype) for i in inputs)
  1147. def make_dev_tensor(value, dtype=None, device=None):
  1148. return tensor(value, dtype=dtype, device=device)._dev_tensor()
  1149. for testcase in feeds["testcases"]:
  1150. assert isinstance(testcase, dict)
  1151. cg = G.Graph()
  1152. output_mgbvars = []
  1153. for name, dtype in inputs:
  1154. output_mgbvars.append(
  1155. cg.make_const(
  1156. make_dev_tensor(
  1157. testcase.pop(name), dtype=dtype, device="cpux"
  1158. )
  1159. )
  1160. )
  1161. assert not testcase, "extra inputs provided in testcase: {}".format(
  1162. testcase.keys()
  1163. )
  1164. dump_content, _ = G.dump_graph(
  1165. output_mgbvars, strip_info_file=strip_info_file, append_json=True,
  1166. )
  1167. file.write(dump_content)
  1168. return dump_info
  1169. def _process_inputs(self, *args, **kwargs):
  1170. if self._untraced:
  1171. self._inputs_to_restore = []
  1172. def record_input(x):
  1173. if x is None:
  1174. return
  1175. h, info = self._new_handle()
  1176. info.external = False
  1177. info.name = x.c_name
  1178. info.device = x.device
  1179. info.dtype = x.dtype
  1180. info.shape = x.numpy().shape
  1181. x._mixin_handle = h
  1182. x._recording = True
  1183. x._trace_mixin_info = info
  1184. self._inputs_to_restore.append(x)
  1185. return h
  1186. self._arg_bindings = []
  1187. for i, x in enumerate(args):
  1188. if not isinstance(x, RawTensor):
  1189. raise TypeError(
  1190. "positional arguments should all be tensor "
  1191. "but args[%d] cannot be recognized as one" % i
  1192. )
  1193. self._arg_bindings.append(record_input(x))
  1194. self._kwarg_bindings = {}
  1195. for k, x in kwargs.items():
  1196. if isinstance(x, RawTensor):
  1197. self._kwarg_bindings[k] = record_input(x)
  1198. else:
  1199. if len(args) != len(self._arg_bindings):
  1200. raise TraceMismatchError("positional argument length mismatch")
  1201. self._tensor_remaps = {}
  1202. for i, (h, x) in enumerate(zip(self._arg_bindings, args)):
  1203. if not isinstance(x, RawTensor):
  1204. raise TypeError(
  1205. "positional arguments should all be tensor "
  1206. "but args[%d] cannot be recognized as one" % i
  1207. )
  1208. info = self._tinfo[h]
  1209. if x.dtype != info.dtype:
  1210. raise TypeError("args[%d].dtype different from last time" % i)
  1211. if x.device != info.device:
  1212. raise TypeError("args[%d].device different from last time" % i)
  1213. info.data_setter.set_value(x._dev_tensor())
  1214. self._tensor_remaps[x._handle] = CompiledTensorProxy(h)
  1215. kwargs_tensors = {}
  1216. for k, x in kwargs.items():
  1217. if isinstance(x, RawTensor):
  1218. kwargs_tensors[k] = x
  1219. if set(kwargs_tensors) != set(self._kwarg_bindings):
  1220. too_many = set(kwargs_tensors) - set(self._kwarg_bindings)
  1221. too_few = set(self._kwarg_bindings) - set(kwargs_tensors)
  1222. if too_many:
  1223. raise TraceMismatchError(
  1224. "keyword arguments found to be tensor this time "
  1225. "but were non-tensor previously: %s" % " ".join(too_many)
  1226. )
  1227. if too_few:
  1228. raise TraceMismatchError(
  1229. "keyword arguments found to be non-tensor this time "
  1230. "but were tensor previously: %s" % " ".join(too_few)
  1231. )
  1232. for k, h in self._kwarg_bindings.items():
  1233. x = kwargs_tensors[k]
  1234. info = self._tinfo[h]
  1235. if x.dtype != info.dtype:
  1236. raise TypeError("kwargs[%s].dtype different from last time" % k)
  1237. if x.device != info.device:
  1238. raise TypeError("kwargs[%s].device different from last time" % k)
  1239. info.data_setter.set_value(x._dev_tensor())
  1240. self._tensor_remaps[x._handle] = CompiledTensorProxy(h)
  1241. def _process_outputs(self, outputs):
  1242. output_names = None
  1243. if isinstance(outputs, collections.abc.Mapping):
  1244. output_names, outputs = zip(*sorted(outputs.items()))
  1245. elif not isinstance(outputs, collections.abc.Sequence):
  1246. outputs = (outputs,)
  1247. if not self._untraced:
  1248. if output_names != self._output_names:
  1249. too_many = set(output_names) - set(self._output_names)
  1250. too_few = set(self._output_names) - set(output_names)
  1251. if too_many:
  1252. raise TraceMismatchError(
  1253. "output has more keys than last time: %s" % " ".join(too_many)
  1254. )
  1255. if too_few:
  1256. raise TraceMismatchError(
  1257. "output has less keys than last time: %s" % " ".join(too_few)
  1258. )
  1259. if len(outputs) != len(self._output_bindings):
  1260. raise TraceMismatchError("output size differs from last time")
  1261. else:
  1262. self._output_names = output_names
  1263. self._output_bindings = []
  1264. for i, x in enumerate(outputs):
  1265. if not isinstance(x, RawTensor):
  1266. raise TypeError("every item of return value should be tensor")
  1267. if self._untraced:
  1268. h = x._mixin_handle
  1269. if h < 0:
  1270. raise RuntimeError("output is not computed from inputs")
  1271. self._output_bindings.append(h)
  1272. else:
  1273. h = x._mixin_handle
  1274. if h not in self._output_handles:
  1275. raise RuntimeError("output is not computed from inputs")
  1276. if h != self._output_bindings[i]:
  1277. raise TraceMismatchError(
  1278. "retval[%s] is a different tensor than last time"
  1279. % (output_names and output_names[i] or i)
  1280. )
  1281. def get_profile(self):
  1282. r"""Get profiling result for compiled trace.
  1283. Return:
  1284. a json compatible object.
  1285. """
  1286. if not self._profiler:
  1287. raise RuntimeError("trace is not set with profiling=True")
  1288. return json.loads(self._profiler.get())
  1289. class CompiledTensorProxy:
  1290. r"""Duck-typed RawTensor"""
  1291. def __init__(self, handle):
  1292. self.__handle = handle
  1293. self._isscalar = False
  1294. self.__info = active_trace._tinfo[handle]
  1295. self.__shape = None
  1296. self.__data = None
  1297. self.__value = None
  1298. @property
  1299. def dtype(self):
  1300. return self.__info.varnode.dtype
  1301. @property
  1302. def device(self):
  1303. return self.__info.varnode.device
  1304. @property
  1305. def shape(self):
  1306. if self._isscalar:
  1307. return ()
  1308. if self.__shape is None:
  1309. if self.__info.shape_read:
  1310. self.__shape = self.__info.shape_reader.get_value().shape
  1311. elif self.__info.data_read:
  1312. self.__shape = self._dev_tensor().shape
  1313. else:
  1314. # c++ will throw TraceReadError
  1315. return None
  1316. return self.__shape
  1317. def numpy(self):
  1318. if self.__value is None:
  1319. if self.__info.value_read:
  1320. self.__value = self.__info.value_reader.get_value()
  1321. elif self.__info.data_read:
  1322. self.__value = self._dev_tensor().numpy()
  1323. else:
  1324. # c++ will throw TraceReadError
  1325. return None
  1326. # c++ side will handle scalar case
  1327. return self.__value
  1328. def _dev_tensor(self):
  1329. if self.__data is None:
  1330. if not self.__info.data_read:
  1331. # c++ will throw TraceReadError
  1332. return None
  1333. self.__data = self.__info.data_reader.get_value()
  1334. return self.__data
  1335. def __del__(self):
  1336. if self.__info.shape_read and self.__shape is not None:
  1337. self.__info.shape_reader.drop_value()
  1338. if self.__info.value_read and self.__value is not None:
  1339. self.__info.value_reader.drop_value()
  1340. if self.__info.data_read and self.__data is not None:
  1341. self.__info.data_reader.drop_value()
  1342. def apply_symbolic_mode(op: OpDef, *args: RawTensor):
  1343. graph = active_trace._lazy_eval_graph
  1344. ivars = []
  1345. for x in args:
  1346. var = getattr(x, "_varnode", None)
  1347. if var:
  1348. ivars.append(var)
  1349. else:
  1350. data_setter = G.InputNode(
  1351. device=x.device,
  1352. dtype=x.dtype,
  1353. shape=x.numpy().shape or (1,),
  1354. graph=graph,
  1355. use_static_shape=True,
  1356. )
  1357. var = data_setter.outputs[0]
  1358. ivars.append(var)
  1359. data_setter.set_value(x._dev_tensor())
  1360. require_links = type(op) in _io_op_types
  1361. if require_links and active_trace._lazy_eval_links:
  1362. assert len(ivars) > 0, "op should has at least one input"
  1363. opnode = G.VirtualDepNode(
  1364. [ivars[0], *active_trace._lazy_eval_links],
  1365. str(active_trace._lazy_eval_links[0].device),
  1366. )
  1367. ivars[0] = opnode.outputs[0]
  1368. active_trace._lazy_eval_links = (ivars[0],)
  1369. ovars = G.apply_normal_varnode(op, *ivars)
  1370. outputs = [RawTensor(o) for o in ovars]
  1371. if require_links:
  1372. active_trace._lazy_eval_links = (G.VarNode(outputs[0]._varnode),)
  1373. return outputs
  1374. def apply_const_symbolic_mode(value, dtype, device, name):
  1375. graph = active_trace._lazy_eval_graph
  1376. # don't need to unset tracing
  1377. # because varnode construction will ignore tracing flag
  1378. ret = RawTensor(graph.make_const(value, dtype=dtype, device=device, name=name))
  1379. if np.array(value).ndim == 0:
  1380. setscalar(ret)
  1381. return (ret,)
  1382. def apply_compiled_mode(op: OpDef, *args: RawTensor):
  1383. if skip_tracing:
  1384. args = [
  1385. RawTensor(x._dev_tensor()) if x.__class__ is CompiledTensorProxy else x
  1386. for x in args
  1387. ]
  1388. unset_tracing()
  1389. ret = apply(op, *args)
  1390. set_tracing()
  1391. return ret
  1392. return active_trace._apply_op(op, args)
  1393. def apply_const_compiled_mode(value, dtype, device, is_const, no_cache, name):
  1394. if skip_tracing:
  1395. unset_tracing()
  1396. ret = RawTensor(value, dtype, device, False, name)
  1397. set_tracing()
  1398. return ret
  1399. return active_trace._apply_const(value, dtype, device)
  1400. def apply_with_tracing(op: OpDef, *args: RawTensor):
  1401. if active_trace._graph:
  1402. # if member _graph exits, then is_compiled
  1403. return apply_compiled_mode(op, *args)
  1404. if hasattr(op, "scope"):
  1405. op.scope = AutoNaming.get_scope()
  1406. if active_trace._symbolic:
  1407. outputs = apply_symbolic_mode(op, *args)
  1408. else:
  1409. unset_tracing()
  1410. outputs = apply(op, *args)
  1411. set_tracing()
  1412. active_trace._record_op(op, args, outputs)
  1413. return list(outputs)
  1414. def apply_const_with_tracing(value, dtype, device, is_const, no_cache, name):
  1415. if active_trace._graph:
  1416. return apply_const_compiled_mode(value, dtype, device, is_const, no_cache, name)
  1417. if active_trace._symbolic:
  1418. outputs = apply_const_symbolic_mode(value, dtype, device, name)
  1419. else:
  1420. unset_tracing()
  1421. outputs = RawTensor(value, dtype, device, False, name)
  1422. if np.array(value).ndim == 0:
  1423. setscalar(outputs)
  1424. outputs = (outputs,)
  1425. set_tracing()
  1426. active_trace._record_const(outputs)
  1427. return list(outputs)