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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. import sys
  19. from typing import Any
  20. import cv2
  21. import numpy as np
  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 Trace, TraceError, name_tensor # skip_tracing,
  27. from ..core._imperative_rt.graph import _set_priority_to_id
  28. from ..core._imperative_rt.ops import (
  29. AssertEqual,
  30. CollectiveComm,
  31. ExternOpr,
  32. RemoteRecv,
  33. RemoteSend,
  34. )
  35. from ..core._trace_option import set_symbolic_shape
  36. from ..core.tensor import megbrain_graph as G
  37. from ..logger import get_logger
  38. from ..utils import comp_graph_tools as cgtools
  39. from ..utils.naming import AutoNaming
  40. from ..utils.profiler import is_profiling
  41. from .dtr_config import DTRConfig
  42. from .graph_opt_config import GraphOptimizationConfig
  43. from .sublinear_memory_config import SublinearMemoryConfig
  44. logger = get_logger(__name__)
  45. def _input_node_use_static_shape():
  46. return os.environ.get("MEGENGINE_INPUT_NODE_USE_STATIC_SHAPE") is not None
  47. active_trace = None
  48. skip_tracing = False
  49. def is_tracing():
  50. if active_trace is None:
  51. return False
  52. else:
  53. return not skip_tracing
  54. @contextlib.contextmanager
  55. def exclude_from_trace():
  56. global skip_tracing
  57. if skip_tracing or (active_trace is None):
  58. yield
  59. return
  60. try:
  61. skip_tracing = True
  62. if active_trace is not None:
  63. active_trace._begin_excluded_region()
  64. yield
  65. if active_trace is not None:
  66. active_trace._end_excluded_region()
  67. finally:
  68. skip_tracing = False
  69. def array_comparator(lhs, rhs):
  70. return np.all(lhs == rhs)
  71. class trace:
  72. """Wraps a callable and provide:
  73. * tracing via :meth:`.trace` and :meth:`.dump`
  74. * accelerated evalutaion via :meth:`.__call__`
  75. Args:
  76. function: the function will be traced.
  77. symbolic: whether to apply symbolic execution for tracing. Default: False
  78. capture_as_const: capture global vars or closures as const value. Default: False
  79. record_only: if True, won't run even if call the function. Default: False
  80. sublinear_memory_config: configuration for sublinear memory optimization.
  81. If not None, it enables sublinear memory optimization with given setting.
  82. profiling: whether to profile compiled trace. Default: False
  83. opt_level: optimization level for compiling trace. Default: 2
  84. graph_opt_config: configuration for graph optimization. Default: None
  85. symbolic_shape: whether to use symbolic shape for tracing. Default: True
  86. """
  87. def __new__(cls, *args, **kwargs):
  88. if not args:
  89. return functools.partial(cls, **kwargs)
  90. return super().__new__(cls)
  91. def __init__(
  92. self,
  93. function,
  94. symbolic=False,
  95. capture_as_const=False,
  96. record_only=False,
  97. sublinear_memory_config: SublinearMemoryConfig = None,
  98. dtr_config: DTRConfig = None,
  99. profiling: bool = False,
  100. opt_level: int = 2,
  101. graph_opt_config: GraphOptimizationConfig = None,
  102. symbolic_shape: bool = True,
  103. ):
  104. self.__wrapped__ = function
  105. self._capture_as_const = capture_as_const or record_only
  106. self._arg_bindings = None
  107. self._kwarg_bindings = None
  108. self._output_bindings = None
  109. self._symbolic_shape = symbolic_shape
  110. self._graph_options = {
  111. "no_force_inplace": True,
  112. "graph_opt_level": opt_level,
  113. "seq_opt.enable_seq_comp_node_opt": False,
  114. }
  115. # prevent cyclic reference
  116. graph_options = self._graph_options
  117. if dtr_config is not None:
  118. graph_options["enable_dtr_memory_opt"] = True
  119. graph_options[
  120. "dtr_config.eviction_threshold"
  121. ] = dtr_config.eviction_threshold
  122. graph_options[
  123. "dtr_config.evictee_minimum_size"
  124. ] = dtr_config.evictee_minimum_size
  125. graph_options[
  126. "dtr_config.recomp_memory_factor"
  127. ] = dtr_config.recomp_memory_factor
  128. graph_options[
  129. "dtr_config.recomp_time_factor"
  130. ] = dtr_config.recomp_time_factor
  131. if graph_opt_config is not None:
  132. mapping = {None: 0, False: 1, True: 2}
  133. graph_options["graph_opt.jit_config.fuse_dimshuffle"] = mapping[
  134. graph_opt_config.jit_fuse_dimshuffle
  135. ]
  136. graph_options["graph_opt.jit_config.fuse_reduce"] = mapping[
  137. graph_opt_config.jit_fuse_reduce
  138. ]
  139. if sublinear_memory_config is not None:
  140. graph_options["enable_sublinear_memory_opt"] = True
  141. graph_options[
  142. "sublinear_mem_config.lb_memory_mb"
  143. ] = sublinear_memory_config.lb_memory_mb
  144. graph_options[
  145. "sublinear_mem_config.genetic_nr_iter"
  146. ] = sublinear_memory_config.genetic_nr_iter
  147. graph_options[
  148. "sublinear_mem_config.genetic_pool_size"
  149. ] = sublinear_memory_config.genetic_pool_size
  150. graph_options[
  151. "sublinear_mem_config.thresh_nr_try"
  152. ] = sublinear_memory_config.thresh_nr_try
  153. graph_options[
  154. "sublinear_mem_config.num_worker"
  155. ] = sublinear_memory_config.num_worker
  156. if int(os.getenv("MEGENGINE_INPLACE_UPDATE", "0")):
  157. graph_options["var_sanity_check_first_run"] = False
  158. def apply_options(options):
  159. for k, v in graph_options.items():
  160. words = k.split(".")
  161. suboptions = options
  162. for word in words[:-1]:
  163. suboptions = getattr(suboptions, word)
  164. setattr(suboptions, words[-1], v)
  165. self._trace = Trace()
  166. self._trace.symbolic = symbolic or record_only
  167. self._trace.capture_as_const = capture_as_const or record_only
  168. self._trace.no_exec = record_only
  169. self._trace.options_visitor = apply_options
  170. self._trace.profile = profiling
  171. self._trace.array_comparator = array_comparator
  172. self._trace.record_input_shapes = _input_node_use_static_shape()
  173. def __call__(self, *args, **kwargs):
  174. global active_trace
  175. symbolic_shape = None
  176. outputs = None
  177. try:
  178. active_trace = self
  179. self._trace.enter()
  180. if self._capture_as_const:
  181. self._process_inputs(*args, **kwargs)
  182. symbolic_shape = set_symbolic_shape(self._symbolic_shape)
  183. outputs = self.__wrapped__(*args, **kwargs)
  184. finally:
  185. handling_exc = sys.exc_info() != (None,) * 3
  186. active_trace = None
  187. if symbolic_shape is not None:
  188. symbolic_shape = set_symbolic_shape(symbolic_shape)
  189. assert symbolic_shape == self._symbolic_shape
  190. if self._capture_as_const and (outputs is not None):
  191. self._process_outputs(outputs)
  192. try:
  193. # may raise TraceError
  194. self._trace.exit()
  195. except TraceError:
  196. if not handling_exc:
  197. raise
  198. return outputs
  199. def _process_inputs(self, *args, **kwargs):
  200. for i, arg in enumerate(args):
  201. name_tensor("arg_{}".format(i), arg)
  202. # TODO: mark kwargs in order
  203. for k, kwarg in kwargs.items():
  204. if isinstance(kwarg, RawTensor):
  205. name_tensor("kwarg_{}".format(k), kwarg)
  206. if self._arg_bindings is None:
  207. self._arg_bindings = [
  208. ("arg_{}".format(i), arg._tuple_shape) for i, arg in enumerate(args)
  209. ]
  210. if self._kwarg_bindings is None:
  211. self._kwarg_bindings = {
  212. "kwarg_{}".format(k): (k, kwarg._tuple_shape)
  213. for k, kwarg in kwargs.items()
  214. if isinstance(kwarg, RawTensor)
  215. }
  216. def _process_outputs(self, outputs):
  217. if isinstance(outputs, RawTensor):
  218. outputs = [outputs]
  219. if isinstance(outputs, collections.abc.Mapping):
  220. output_names, outputs = zip(*sorted(outputs.items()))
  221. else:
  222. # output_names = ["output_{}".format(i) for i in range(len(outputs))]
  223. output_names = None
  224. self._output_names = output_names
  225. for i, output in enumerate(outputs):
  226. name_tensor("output_{}".format(i), output)
  227. if self._output_bindings is None:
  228. self._output_bindings = ["output_{}".format(i) for i in range(len(outputs))]
  229. def _begin_excluded_region(self):
  230. self._trace.begin_excluded_region()
  231. def _end_excluded_region(self):
  232. self._trace.end_excluded_region()
  233. def _make_feed(
  234. self,
  235. graph,
  236. outputs,
  237. input_data,
  238. repeat,
  239. silent,
  240. no_assert,
  241. maxerr,
  242. resize_input,
  243. input_transform,
  244. ):
  245. def auto_reformat_image(path, data, dst_shape):
  246. """reformat image to target shape
  247. :param data: image data as numpy array
  248. :param dst_shape: target shape
  249. """
  250. dim3_format = False # required input format does not contain batch
  251. hwc_format = False # required input format is NHWC
  252. if not dst_shape: # input tensor shape is not predefined
  253. if len(data.shape) == 2:
  254. chl = 1
  255. h = data.shape[0]
  256. w = data.shape[1]
  257. else:
  258. assert (
  259. len(data.shape) == 3
  260. ), "Input image must be of dimension 2 or 3"
  261. h, w, chl = data.shape
  262. dst_shape = (1, chl, h, w)
  263. if len(dst_shape) == 3:
  264. dst_shape = (1,) + dst_shape
  265. dim3_format = True
  266. assert len(dst_shape) == 4, "bad dst_shape: {}".format(dst_shape)
  267. chl = dst_shape[1]
  268. if chl in [1, 3]:
  269. n, c, h, w = dst_shape
  270. dst_shape = (n, h, w, c)
  271. else:
  272. chl = dst_shape[3]
  273. assert chl in [
  274. 1,
  275. 3,
  276. ], "can not infer input format from shape: {}".format(dst_shape)
  277. hwc_format = True
  278. # dst_shape has now been normalized to NHWC format
  279. if resize_input:
  280. h, w = dst_shape[1:3]
  281. data = cv2.resize(data, (w, h))
  282. logger.info("input {} resized to {}".format(path, data.shape))
  283. if chl == 1:
  284. data = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)
  285. data = data[:, :, np.newaxis]
  286. assert data.ndim == 3
  287. data = data[np.newaxis]
  288. # data normalized to NHWC format
  289. if not hwc_format:
  290. data = np.transpose(data, (0, 3, 1, 2))
  291. if dim3_format:
  292. data = np.squeeze(data, 0)
  293. return data
  294. def read_input_data(dst_shape, dtype, path):
  295. def check_shape_equal(dst_shape, data_shape):
  296. if len(dst_shape):
  297. assert len(data_shape) == len(
  298. dst_shape
  299. ), "input/data shapes mismatch: {} vs {}".format(
  300. dst_shape, data_shape
  301. )
  302. if data_shape[1:] != dst_shape[1:]:
  303. logger.warning(
  304. "dst_shape is {}; data_shape is {}".format(
  305. dst_shape, data_shape
  306. )
  307. )
  308. if path.startswith("#"):
  309. assert not resize_input
  310. assert not input_transform
  311. spec = path
  312. m = re.match(
  313. r"^#rand\(([-0-9.]*)\s*,\s*([-0-9.]*)\s*(,[^\)]+)?\)$", spec
  314. )
  315. assert m, "bad spec {}".format(spec)
  316. rng_min = float(m.group(1))
  317. rng_max = float(m.group(2))
  318. if m.group(3):
  319. shape_str = m.group(3)
  320. try:
  321. shape = shape_str[1:].split(",")
  322. if shape[-1].strip() == "...":
  323. shape = shape[:-1]
  324. shape.extend(list(dst_shape[len(shape) :]))
  325. data_shape = tuple(map(int, shape))
  326. except ValueError as e:
  327. raise ValueError("bad spec {}: {}".format(spec, e.args))
  328. else:
  329. data_shape = dst_shape
  330. check_shape_equal(dst_shape, data_shape)
  331. return np.random.uniform(rng_min, rng_max, data_shape).astype(dtype)
  332. # try to load image
  333. data = cv2.imread(path, cv2.IMREAD_COLOR)
  334. if data is None:
  335. assert not resize_input
  336. data = np.load(path)
  337. assert isinstance(data, np.ndarray)
  338. else:
  339. # load image succeeds, so we expect input format is image format
  340. data = auto_reformat_image(path, data, dst_shape)
  341. data = np.repeat(data, repeat, axis=0)
  342. if repeat > 1:
  343. logger.info(
  344. "repeat input for {} times, data shape is {}".format(
  345. repeat, data.shape
  346. )
  347. )
  348. check_shape_equal(dst_shape, data.shape)
  349. if input_transform:
  350. data = eval(input_transform, {"data": data, "np": np})
  351. return data
  352. def gen_one_testcase(inputs, spec):
  353. paths = spec.split(";")
  354. if len(paths) != len(inputs):
  355. if len(paths) == 1 and paths[0].startswith("#"):
  356. paths = ["{}:{}".format(name, paths[0]) for name in inputs.keys()]
  357. assert len(paths) == len(
  358. inputs
  359. ), "required inputs: {}; data paths: {}".format(inputs.keys(), paths)
  360. if len(paths) == 1 and ":" not in paths[0]:
  361. paths[0] = next(iter(inputs.keys())) + ":" + paths[0]
  362. ret = {}
  363. for path in paths:
  364. var, path = path.split(":")
  365. ret[var] = read_input_data(inputs[var].shape, inputs[var].dtype, path)
  366. return ret
  367. inputs = cgtools.get_dep_vars(outputs, "Host2DeviceCopy")
  368. inputs = {i.name: i for i in inputs}
  369. if not no_assert:
  370. replace_varmap = {}
  371. inp_map = {}
  372. # replace var use InputNode
  373. for name, var in inputs.items():
  374. inp = G.InputNode(
  375. device="xpux", dtype=var.dtype, shape=var.shape, graph=graph
  376. )
  377. replace_varmap[var] = inp.outputs[0]._node
  378. inp_map[name] = inp
  379. new = cgtools.replace_vars(outputs, replace_varmap)
  380. if isinstance(new, rt.VarNode):
  381. new = list(new)
  382. output_nodes = [G.OutputNode(var) for var in new]
  383. func = graph.compile(*[node.outputs[0]._node for node in output_nodes])
  384. def make_dev_tensor(value, dtype=None, device=None):
  385. return tensor(value, dtype=dtype, device=device)._dev_tensor()
  386. def calculate(*args, **kwargs):
  387. output_val = []
  388. # set inputs value
  389. for name, var in inputs.items():
  390. val = kwargs.pop(name, None)
  391. assert val is not None, "miss input name{}".format(name)
  392. dev_tensor = make_dev_tensor(val, dtype=var.dtype, device="xpux")
  393. inp_map[name].set_value(dev_tensor)
  394. func.execute()
  395. for res in output_nodes:
  396. output_val.append(res.get_value().numpy())
  397. return output_val
  398. def expect_name(var):
  399. return "{}:expect".format(var.name)
  400. testcases = []
  401. np.set_printoptions(precision=2, threshold=4, suppress=True)
  402. data_list = []
  403. for item in input_data:
  404. if item.startswith("@"):
  405. with open(item[1:], "r") as f:
  406. data_list.extend(
  407. [line.rstrip() for line in f if line.rstrip() != ""]
  408. )
  409. else:
  410. data_list.append(item)
  411. for inp_spec in data_list:
  412. cur_testcase = gen_one_testcase(inputs, inp_spec)
  413. assert len(cur_testcase) == len(
  414. inputs
  415. ), "required inputs: {}; given data: {}".format(
  416. inputs.keys(), cur_testcase.keys()
  417. )
  418. if not no_assert:
  419. outputs_get = calculate(**cur_testcase)
  420. for var, val in zip(outputs, outputs_get):
  421. cur_testcase[expect_name(var)] = val
  422. logger.info(
  423. "generate test groundtruth: var={} shape={} range=({}, {})"
  424. " mean={} var={}".format(
  425. var,
  426. val.shape,
  427. val.min(),
  428. val.max(),
  429. np.mean(val),
  430. np.var(val),
  431. )
  432. )
  433. testcases.append(cur_testcase)
  434. logger.info(
  435. "add testcase: \n {}".format(
  436. "\n ".join(
  437. "{}: shape={} dtype={} range=({:.2f},{:.2f}) "
  438. "mean={:.2f} sd={:.2f}".format(
  439. k, v.shape, v.dtype, v.min(), v.max(), np.mean(v), np.std(v)
  440. )
  441. for k, v in sorted(cur_testcase.items())
  442. )
  443. )
  444. )
  445. if not no_assert:
  446. def expect_shp(var):
  447. ret = var.shape
  448. if ret:
  449. return ret
  450. return testcases[0][expect_name(var)].shape
  451. def assert_equal(expect, real, **kwargs):
  452. op = AssertEqual(**kwargs)
  453. (res,) = G.apply_normal_varnode(op, expect, real)
  454. return res._node
  455. verbose = not silent
  456. outputs_new = []
  457. for i in outputs:
  458. device = rt.CompNode("xpux")
  459. dtype = i.dtype
  460. name = expect_name(i)
  461. shape = expect_shp(i)
  462. # make expect output as one input of model.
  463. expect_get = rt.make_h2d(graph, device, dtype, shape, name)
  464. # insert assert opr to check expect and real.
  465. outputs_new.append(
  466. assert_equal(expect_get, i, verbose=verbose, maxerr=maxerr,)
  467. )
  468. inputs[expect_name(i)] = expect_get
  469. outputs = outputs_new
  470. return {"outputs": outputs, "testcases": testcases}
  471. def dump(
  472. self,
  473. file,
  474. *,
  475. arg_names=None,
  476. output_names=None,
  477. append=False,
  478. keep_var_name: int = 1,
  479. keep_opr_name: bool = False,
  480. keep_param_name: bool = False,
  481. keep_opr_priority: bool = False,
  482. strip_info_file=None,
  483. append_json=False,
  484. optimize_for_inference=True,
  485. user_info: Any = None,
  486. enable_metadata: bool = True,
  487. input_data=None,
  488. repeat=1,
  489. silent=False,
  490. no_assert=False,
  491. maxerr=1e-4,
  492. resize_input=False,
  493. input_transform=None,
  494. dump_format: str = None,
  495. **kwargs
  496. ):
  497. r"""Serializes trace to file system.
  498. Args:
  499. file: output file, could be file object or filename.
  500. arg_names: names of the input tensors in the traced function.
  501. output_names: names of the output tensors in the traced function,
  502. use the default name if not specified.
  503. append: whether output is appended to ``file``.
  504. Only works when ``file`` is str.
  505. keep_var_name: level for keeping variable names:
  506. * 0: none of the names are kept
  507. * 1: (default)keep names of output vars
  508. * 2: keep names of all (output and internal) vars
  509. keep_opr_name: whether to keep operator names.
  510. keep_param_name: whether to keep param names, so param values can be
  511. easily manipulated after loading model
  512. keep_opr_priority: whether to keep priority setting for operators
  513. strip_info_file: a string for path or a file handler. if is not None,
  514. then the dump information for code strip would be written to ``strip_info_file``
  515. append_json: will be check when `strip_info_file` is not None. if set
  516. true, the information for code strip will be append to strip_info_file.
  517. if set false, will rewrite strip_info_file
  518. optimize_for_inference: enbale optmizations,
  519. will skip all optimize options if this is False. Default: True
  520. user_info: any type object, which will be pickled to bytes.
  521. enable_metadata: whether to save metadata into output file.
  522. input_data: input test data and current network output would be used as groundtruth.
  523. The format is "var0:file0;var1:file1..." to specify data files for input vars.
  524. It can also be "#rand(min,max,shape...)" for generating random input data, for
  525. example, "#rand(0,255)", "#rand(0,255,1,3,224,224)" or "#rand(0, 255, 1, ...)"
  526. where `...` means the remaining part of the original shape. If the shape is not
  527. specified, the shape of corresponding input tensors in the network will be used.
  528. If there is only one input var, its name can be omitted. Each data file can either
  529. be an image which can be loaded by opencv, or a pickled numpy.ndarray. This option
  530. can be given multiple times to add multiple testcases. If you start the data
  531. with the letter @, the rest should be a filename, and each line in the file should
  532. be a single datum in the format described above. *NOTE* If `input_data` is not None,
  533. you can only use load-and-run to run the output file.
  534. repeat: how many times the input image is repeated. Useful when running benchmark for
  535. batch size other than one. Have no effect on randomly generated input data.
  536. silent: whether set verbose to False in assert_equal opr.
  537. no_assert: whether insert assert_equal opr to check result; this option is useful for
  538. benchmarking.
  539. maxerr: max error for assert_equal check during runtime.
  540. resize_input: whether resize input image to fit input var shape.
  541. input_transform: a python expression to transform the input data.
  542. Example: data / np.std(data)
  543. dump_format: using different dump formats. the open source MegEngine defaults to the FBS
  544. format. internal MegEngine have a choice of FBS and internal proprietary formats
  545. Keyword Arguments:
  546. * enable_io16xc32 --
  547. whether to use float16 for I/O between oprs and use
  548. float32 as internal computation precision. Note the output var would be
  549. changed to float16.
  550. * enable_ioc16 --
  551. whether to use float16 for both I/O and computation
  552. precision.
  553. * enable_hwcd4 --
  554. whether to use NHWCD4 data layout. This is faster on some
  555. OpenCL backend.
  556. * enable_nchw88 --
  557. whether to use NCHW88 data layout, currently
  558. used in X86 AVX backend.
  559. * enable_nchw44 --
  560. whether to use NCHW44 data layout, currently
  561. used in arm backend.
  562. * enable_nchw44_dot --
  563. whether to use NCHW44_dot data layout, currently
  564. used in armv8.2+dotprod backend.
  565. * enable_nchw4 --
  566. whether to use NCHW4 data layout, currently
  567. used in nvidia backend(based on cudnn).
  568. * enable_nchw32 --
  569. whether to use NCHW32 data layout, currently
  570. used in nvidia backend with tensorcore(based on cudnn).
  571. * enable_chwn4 --
  572. whether to use CHWN4 data layout, currently
  573. used in nvidia backend with tensorcore.
  574. * enable_nchw64 --
  575. whether to use NCHW64 data layout, used for fast int4
  576. support on Nvidia GPU.
  577. * enable_fuse_conv_bias_nonlinearity: whether to fuse conv+bias+nonlinearty
  578. into one opr.
  579. * enable_fuse_conv_bias_with_z: whether to fuse conv_bias with z
  580. input for inference on nvidia backend(this optimization pass will
  581. result in mismatch of the precision of output of training and
  582. inference)
  583. * enable_fuse_preprocess: whether to fuse astype\pad_channel\dimshuffle and
  584. etc opr
  585. """
  586. if not self._capture_as_const:
  587. raise ValueError(
  588. "you must specify capture_as_const=True at __init__ to use dump"
  589. )
  590. if self._output_names and output_names:
  591. raise TypeError(
  592. "cannot specify output_names when output is already in dict format"
  593. )
  594. if output_names and isinstance(output_names, str):
  595. output_names = (output_names,)
  596. if output_names and len(output_names) != len(self._output_bindings):
  597. raise ValueError(
  598. "wrong number of output_names, should be {} values".format(
  599. len(self._output_bindings)
  600. )
  601. )
  602. prefer_input_names = arg_names is not None
  603. if arg_names is None:
  604. arg_names = ["arg_%d" % i for i in range(len(self._arg_bindings))]
  605. if isinstance(arg_names, str):
  606. arg_names = (arg_names,)
  607. arg_names = [arg_name if arg_name is not None else "" for arg_name in arg_names]
  608. if arg_names and len(arg_names) != len(self._arg_bindings):
  609. raise ValueError(
  610. "wrong number of arg_names, should be {} values".format(
  611. len(self._arg_bindings)
  612. )
  613. )
  614. output_names = output_names or self._output_names
  615. if output_names is None:
  616. output_names = [""] * len(self._output_bindings)
  617. # output_names = ["output_{}".format(i) for i in range(len(self._output_bindings))]
  618. input_bindings = []
  619. def normalize_shape(shape):
  620. return (1,) if shape == () else shape
  621. for arg_name, (arg_id, arg_shape) in zip(arg_names, self._arg_bindings):
  622. input_bindings.append((arg_id, arg_name, normalize_shape(arg_shape)))
  623. for kwarg_id, (kwarg_name, kwarg_shape) in self._kwarg_bindings.items():
  624. input_bindings.append((kwarg_id, kwarg_name, normalize_shape(kwarg_shape)))
  625. graph = G.Graph()
  626. dest_vars = self._trace.dump(
  627. graph,
  628. input_bindings,
  629. [*zip(self._output_bindings, output_names)],
  630. prefer_input_names,
  631. )
  632. # dest_vars = [i._node for i in dest_vars]
  633. if input_data is not None:
  634. feeds = self._make_feed(
  635. graph,
  636. dest_vars,
  637. input_data,
  638. repeat,
  639. silent,
  640. no_assert,
  641. maxerr,
  642. resize_input,
  643. input_transform,
  644. )
  645. assert (
  646. isinstance(feeds, dict) and feeds["testcases"]
  647. ), "testcases can not be empty"
  648. dest_vars = feeds["outputs"]
  649. if optimize_for_inference:
  650. dest_vars, optimize_options = G.optimize_for_inference(dest_vars, **kwargs)
  651. dest_vars = [i._node for i in dest_vars]
  652. metadata = SerializationMetadata()
  653. if enable_metadata:
  654. metadata.user_info = pickle.dumps(user_info)
  655. metadata.is_valid = True
  656. metadata.graph_modified = False
  657. if optimize_for_inference:
  658. metadata.optimize_options = optimize_options
  659. if isinstance(file, str):
  660. permission = "wb" if append == False else "ab"
  661. file = open(file, permission)
  662. if keep_opr_priority:
  663. _set_priority_to_id(dest_vars)
  664. if input_data is not None:
  665. file.write(b"mgbtest0")
  666. file.write(struct.pack("I", len(feeds["testcases"])))
  667. dump_content, dump_info = G.dump_graph(
  668. dest_vars,
  669. keep_var_name=keep_var_name,
  670. keep_opr_name=keep_opr_name,
  671. keep_param_name=keep_param_name,
  672. keep_opr_priority=keep_opr_priority,
  673. strip_info_file=strip_info_file,
  674. append_json=append_json,
  675. metadata=metadata,
  676. dump_format=dump_format,
  677. )
  678. file.write(dump_content)
  679. if input_data is not None:
  680. inputs = cgtools.get_dep_vars(dest_vars, "Host2DeviceCopy")
  681. inputs = sorted((i.name, i.dtype) for i in inputs)
  682. def make_dev_tensor(value, dtype=None, device=None):
  683. return tensor(value, dtype=dtype, device=device)._dev_tensor()
  684. for testcase in feeds["testcases"]:
  685. assert isinstance(testcase, dict)
  686. cg = G.Graph()
  687. output_mgbvars = []
  688. for name, dtype in inputs:
  689. output_mgbvars.append(
  690. cg.make_const(
  691. make_dev_tensor(
  692. testcase.pop(name), dtype=dtype, device="cpux"
  693. )
  694. )
  695. )
  696. assert not testcase, "extra inputs provided in testcase: {}".format(
  697. testcase.keys()
  698. )
  699. dump_content, _ = G.dump_graph(
  700. output_mgbvars, strip_info_file=strip_info_file, append_json=True,
  701. )
  702. file.write(dump_content)
  703. return dump_info
  704. def get_profile(self):
  705. return json.loads(self._trace.get_profile())