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.

api.py 25 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. # This is the Python adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
  2. #
  3. # Copyright 2020 Huawei Technologies Co., Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # ============================================================================
  17. """Providing interface methods."""
  18. import types
  19. import sys
  20. from collections import OrderedDict
  21. from functools import wraps
  22. from mindspore import context
  23. from mindspore import log as logger
  24. from .tensor import Tensor as MsTensor
  25. from .._c_expression import generate_key, Executor_, Tensor, MetaTensor, PynativeExecutor_
  26. from .._c_expression import verify_inputs_signature, init_exec_dataset, _set_dataset_mode_config, init_pipeline
  27. from ..parallel._ps_context import _is_role_pserver
  28. from ..parallel._utils import _get_device_num, _get_global_rank, _need_to_full, _check_full_batch, _to_full_tensor, \
  29. _get_parameter_broadcast, _get_pipeline_stages
  30. # store ms_function class compiled pipeline cache
  31. ms_compile_cache = {}
  32. BROADCAST_PHASE = "_broadcast_"
  33. def _convert_function_arguments(fn, *args):
  34. """
  35. Process the fn default parameters.
  36. Args:
  37. fn (Function): The function to be parsed.
  38. args (tuple): The parameters of the function.
  39. """
  40. arguments_dict = OrderedDict()
  41. parse_method = None
  42. if isinstance(fn, (types.FunctionType, types.MethodType)):
  43. parse_method = fn.__name__
  44. index = 0
  45. for value in args:
  46. arguments_dict[f'arg{index}'] = value
  47. index = index + 1
  48. logger.debug("fn(%r) full parameters dict is: %r", fn, arguments_dict)
  49. converted = True
  50. else:
  51. logger.warning("Find error: fn isn't function or method")
  52. converted = False
  53. return converted, arguments_dict, parse_method
  54. def _wrap_func(fn):
  55. """
  56. Wrapper function, convert return data to tensor or tuple of tensor.
  57. Args:
  58. fn (Function): The function need be wrapped.
  59. Returns:
  60. Function, a new function with return suitable format data.
  61. """
  62. @wraps(fn)
  63. def wrapper(*arg, **kwargs):
  64. results = fn(*arg, **kwargs)
  65. def _convert_data(data):
  66. if isinstance(data, Tensor) and not isinstance(data, MsTensor):
  67. return MsTensor(data)
  68. if isinstance(data, tuple):
  69. return tuple(_convert_data(x) for x in data)
  70. if isinstance(data, list):
  71. return list(_convert_data(x) for x in data)
  72. return data
  73. return _convert_data(results)
  74. return wrapper
  75. def _exec_init_graph(obj, init_phase):
  76. """Execute the parameter initializer graph."""
  77. inst_executor = Executor_.get_instance()
  78. param_dict = OrderedDict()
  79. for name, param in obj.parameters_dict().items():
  80. if not param.is_init:
  81. param_dict[name] = param
  82. param.is_init = True
  83. param.data.init_flag = True
  84. if param_dict:
  85. inst_executor.run_init_graph(param_dict, init_phase)
  86. class _MindSporeFunction:
  87. """
  88. Represents a function compiled by mind expression.
  89. _MindSporeFunction will compile the original function for every combination
  90. of argument types and shapes it is given (as well as their values, optionally).
  91. Args:
  92. fn (Function): The root function to compile.
  93. input_signature (Function): User defines signature to verify input.
  94. obj (Object): If function is a method, obj is the owner of function,
  95. else, obj is none.
  96. """
  97. def __init__(self, fn, input_signature=None, obj=None):
  98. self.fn = fn
  99. self.save_graphs = context.get_context("save_graphs")
  100. self.save_graphs_path = context.get_context("save_graphs_path")
  101. self.input_signature = input_signature
  102. self.obj = None
  103. self.identify_obj = None
  104. if hasattr(obj, fn.__name__):
  105. self.obj = obj
  106. elif obj is not None:
  107. self.identify_obj = obj
  108. self._executor = Executor_.get_instance()
  109. def build_data_init_graph(self, graph_name):
  110. """Build GE data graph and init graph for the given graph name."""
  111. if self.obj is None:
  112. logger.warning("Make sure parameter should not be used in function")
  113. para_dict = OrderedDict()
  114. self._executor.build_data_graph(para_dict, graph_name)
  115. return
  116. self._executor.build_data_graph(self.obj.parameters_dict(), graph_name, self.obj.parameters_broadcast_dict())
  117. init_phase = "init_subgraph" + graph_name[graph_name.find("."):]
  118. _exec_init_graph(self.obj, init_phase)
  119. def compile(self, arguments_dict, method_name):
  120. """Returns pipeline for the given args."""
  121. args_list = tuple(arguments_dict.values())
  122. arg_names = tuple(arguments_dict.keys())
  123. # remove first self parameter when fn is a method
  124. if self.obj is not None:
  125. args_list = args_list[1:]
  126. arg_names = arg_names[1:]
  127. # verify the signature for both function and method
  128. if self.input_signature is not None:
  129. signatures = []
  130. for sig_spec in self.input_signature:
  131. if not isinstance(sig_spec, MetaTensor):
  132. raise TypeError("Input_signature is not MetaTensor")
  133. signatures.append(sig_spec)
  134. is_valid_input = verify_inputs_signature(signatures, args_list)
  135. if not is_valid_input:
  136. raise ValueError("Inputs is incompatible with input signature!")
  137. dic = dict(zip(arg_names, args_list))
  138. generate_name = self.fn.__module__ + "." + self.fn.__name__
  139. self.fn.__parse_method__ = method_name
  140. # replace key with obj info and object ext info when fn is a method
  141. if self.obj is not None:
  142. self.obj.__parse_method__ = method_name
  143. generate_name = self.obj.__module__ + "."
  144. if self.obj.__class__.__name__ != "ClipByNorm":
  145. generate_name = generate_name + str(self.obj.create_time)
  146. if self.identify_obj is not None:
  147. generate_name = generate_name + str(id(self.identify_obj))
  148. key = generate_key(generate_name, dic)
  149. phase = str(key[1]) + generate_name
  150. if key not in ms_compile_cache.keys():
  151. is_compile = False
  152. if self.obj is None:
  153. is_compile = self._executor.compile(self.fn, args_list, phase, True)
  154. else:
  155. is_compile = self._executor.compile(self.obj, args_list, phase, True)
  156. if not is_compile:
  157. raise RuntimeError("Executor compile failed.")
  158. if context.get_context("enable_ge"):
  159. self.build_data_init_graph(phase)
  160. # since function can be redefined, we only cache class method pipeline
  161. if self.obj is not None or self.identify_obj is not None:
  162. ms_compile_cache[key] = phase
  163. return phase
  164. return ms_compile_cache[key]
  165. @_wrap_func
  166. def __call__(self, *args):
  167. init_pipeline()
  168. converted, arguments_dict, parse_method = _convert_function_arguments(self.fn, *args)
  169. if not converted:
  170. raise RuntimeError('Process function parameter is failure')
  171. args_list = tuple(arguments_dict.values())
  172. if self.obj is not None:
  173. args_list = args_list[1:]
  174. phase = self.compile(arguments_dict, parse_method)
  175. if context.get_context("precompile_only"):
  176. return None
  177. new_inputs = []
  178. for i in args_list:
  179. if isinstance(i, Tensor):
  180. new_inputs.append(i)
  181. elif context.get_context("grad_for_scalar") and isinstance(i, (int, float)):
  182. new_inputs.append(i)
  183. return self._executor(tuple(new_inputs), phase)
  184. def ms_function(fn=None, obj=None, input_signature=None):
  185. """
  186. Create a callable MindSpore graph from a python function.
  187. This allows the MindSpore runtime to apply optimizations based on graph.
  188. Args:
  189. fn (Function): The Python function that will be run as a graph. Default: None.
  190. obj (Object): The Python Object that provides the information for identifying the compiled function.Default:
  191. None.
  192. input_signature (Tensor): The Tensor which describes the input arguments. The shape and dtype of the Tensor
  193. will be supplied to this function. If input_signature is specified, each input to `fn` must be a `Tensor`.
  194. And the input parameters of `fn` cannot accept `**kwargs`. The shape and dtype of actual inputs should
  195. keep the same as input_signature. Otherwise, TypeError will be raised. Default: None.
  196. Returns:
  197. Function, if `fn` is not None, returns a callable function that will execute the compiled function; If `fn` is
  198. None, returns a decorator and when this decorator invokes with a single `fn` argument, the callable function is
  199. equal to the case when `fn` is not None.
  200. Examples:
  201. >>> from mindspore.ops import functional as F
  202. ...
  203. >>> x = Tensor(np.ones([1, 1, 3, 3]).astype(np.float32))
  204. >>> y = Tensor(np.ones([1, 1, 3, 3]).astype(np.float32))
  205. ...
  206. >>> # create a callable MindSpore graph by calling ms_function
  207. >>> def tensor_add(x, y):
  208. ... z = x + y
  209. ... return z
  210. ...
  211. >>> tensor_add_graph = ms_function(fn=tensor_add)
  212. >>> out = tensor_add_graph(x, y)
  213. ...
  214. >>> # create a callable MindSpore graph through decorator @ms_function
  215. >>> @ms_function
  216. ... def tensor_add_with_dec(x, y):
  217. ... z = x + y
  218. ... return z
  219. ...
  220. >>> out = tensor_add_with_dec(x, y)
  221. ...
  222. >>> # create a callable MindSpore graph through decorator @ms_function with input_signature parameter
  223. >>> @ms_function(input_signature=(Tensor(np.ones([1, 1, 3, 3]).astype(np.float32)),
  224. ... Tensor(np.ones([1, 1, 3, 3]).astype(np.float32))))
  225. ... def tensor_add_with_sig(x, y):
  226. ... z = x + y
  227. ... return z
  228. ...
  229. >>> out = tensor_add_with_sig(x, y)
  230. """
  231. def wrap_mindspore(func):
  232. @wraps(func)
  233. def staging_specialize(*args):
  234. process_obj = obj
  235. if args and not isinstance(args[0], MsTensor) and hasattr(args[0], func.__name__):
  236. process_obj = args[0]
  237. return _MindSporeFunction(func, input_signature, process_obj)(*args)
  238. return staging_specialize
  239. if fn is not None:
  240. return wrap_mindspore(fn)
  241. return wrap_mindspore
  242. def _generate_pip_args(obj, *args, method="construct"):
  243. """Generate arguments for pipeline."""
  244. if hasattr(obj, method):
  245. fn = getattr(obj, method)
  246. else:
  247. raise AttributeError('The process method is not exist')
  248. converted, arguments_dict, parse_method = _convert_function_arguments(fn, *args)
  249. if not converted:
  250. raise RuntimeError('Process method parameter is failure')
  251. args_list = tuple(arguments_dict.values())
  252. args_names = tuple(arguments_dict.keys())
  253. obj.__parse_method__ = parse_method
  254. return args_names, args_list
  255. def _get_auto_split_param_names(parameter_layout_dict):
  256. auto_split_param_names = []
  257. for key, value in parameter_layout_dict.items():
  258. for dim in value[1]:
  259. if dim != -1:
  260. auto_split_param_names.append(key)
  261. break
  262. return auto_split_param_names
  263. def _build_broadcast_graph(broadcast_params_dict, broadcast_phase):
  264. """Build broadcast graph."""
  265. from mindspore.nn.wrap.cell_wrapper import _BroadCastCell
  266. if not broadcast_params_dict:
  267. broadcast_params_dict = {}
  268. broadcast_params = []
  269. for param in broadcast_params_dict.values():
  270. broadcast_params.append(Tensor(param.asnumpy()))
  271. _broadcast_net = _BroadCastCell(broadcast_params)
  272. _broadcast_net.phase = broadcast_phase
  273. broadcasted_params = _broadcast_net()
  274. for param_name, param in zip(broadcast_params_dict.keys(), broadcasted_params):
  275. broadcast_params_dict[param_name].set_data(param)
  276. def _parameter_broadcast(obj, auto_parallel_mode):
  277. """Parameter broadcast."""
  278. auto_split_param_names = []
  279. if auto_parallel_mode:
  280. auto_split_param_names = _get_auto_split_param_names(obj.parameter_layout_dict)
  281. broadcast_params_dict = obj.parameters_broadcast_dict()
  282. if auto_split_param_names and broadcast_params_dict:
  283. broadcast_params_dict = OrderedDict()
  284. for param_name, param in obj.parameters_broadcast_dict().items():
  285. if param_name not in auto_split_param_names:
  286. broadcast_params_dict[param_name] = param
  287. broadcast_phase = "_broadcast_subgraph"
  288. _build_broadcast_graph(broadcast_params_dict, broadcast_phase)
  289. class _PynativeExecutor:
  290. """
  291. An pynative executor used to compile/manage/run graph.
  292. Returns:
  293. Graph, return the result of pipeline running.
  294. """
  295. def __init__(self):
  296. self._executor = PynativeExecutor_.get_instance()
  297. def new_graph(self, obj, *args, **kwargs):
  298. self._executor.new_graph(obj, *args, *(kwargs.values()))
  299. def end_graph(self, obj, output, *args, **kwargs):
  300. self._executor.end_graph(obj, output, *args, *(kwargs.values()))
  301. def check_graph(self, obj, *args, **kwargs):
  302. return self._executor.check_graph(obj, *args, *(kwargs.values()))
  303. def check_run(self, obj, *args, **kwargs):
  304. return self._executor.check_run(obj, *args, *(kwargs.values()))
  305. def grad(self, grad, obj, weights, *args, **kwargs):
  306. self._executor.grad_net(grad, obj, weights, *args, *(kwargs.values()))
  307. def del_cell(self, cell_id=""):
  308. self._executor.clear_cell(cell_id)
  309. def clear_grad(self, obj, *args, **kwargs):
  310. self._executor.clear_grad(obj, *args, *(kwargs.values()))
  311. def sync(self):
  312. self._executor.sync()
  313. def set_grad_flag(self, flag):
  314. self._executor.set_grad_flag(flag)
  315. def enter_construct(self, cell):
  316. self._executor.enter_construct(cell)
  317. def leave_construct(self, cell):
  318. self._executor.leave_construct(cell)
  319. def parameter_broadcast(self, obj, phase, auto_parallel_mode):
  320. if BROADCAST_PHASE not in phase and _get_parameter_broadcast():
  321. _parameter_broadcast(obj, auto_parallel_mode)
  322. def __call__(self, obj, *args, **kwargs):
  323. args = args + tuple(kwargs.values())
  324. return self._executor(obj, args, "")
  325. class _Executor:
  326. """
  327. An executor used to compile/manage/run graph.
  328. Including data_graph, train_graph, eval_graph and predict graph.
  329. Returns:
  330. Graph, return the result of pipeline running.
  331. """
  332. def __init__(self):
  333. # create needed graph by lazy mode
  334. self.is_init = False
  335. self._executor = Executor_.get_instance()
  336. self.compile_cache = {}
  337. self._executor.set_py_exe_path(sys.executable)
  338. def init_dataset(self, queue_name, dataset_size, batch_size, dataset_types, dataset_shapes,
  339. input_indexs, phase='dataset'):
  340. """
  341. Initialization interface for calling data subgraph.
  342. Args:
  343. queue_name (str): The name of tdt queue on the device.
  344. dataset_size (int): The size of dataset.
  345. batch_size (int): The size of batch.
  346. dataset_types (list): The output types of element in dataset.
  347. dataset_shapes (list): The output shapes of element in dataset.
  348. input_indexs (list): The index of data with net.
  349. phase (str): The name of phase, e.g., train_dataset/eval_dataset. Default: 'dataset'.
  350. Returns:
  351. bool, specifies whether the data subgraph was initialized successfully.
  352. """
  353. if not init_exec_dataset(queue_name=queue_name,
  354. size=dataset_size,
  355. batch_size=batch_size,
  356. types=dataset_types,
  357. shapes=dataset_shapes,
  358. input_indexs=input_indexs,
  359. phase=phase):
  360. raise RuntimeError("Failure to init and dataset subgraph!")
  361. return True
  362. def _build_data_graph(self, obj, phase):
  363. self._executor.build_data_graph(obj.parameters_dict(), phase, obj.parameters_broadcast_dict())
  364. def _set_dataset_mode(self, args_list):
  365. """set dataset mode."""
  366. # decide whether to sink based on whether the inputs is virtual or args_list is ()
  367. if (args_list and isinstance(args_list[0], Tensor) and args_list[0].virtual_flag) or \
  368. (args_list is not None and args_list == ()):
  369. _set_dataset_mode_config('sink')
  370. else:
  371. _set_dataset_mode_config('normal')
  372. def compile(self, obj, *args, phase='predict', do_convert=True, auto_parallel_mode=False):
  373. """
  374. Compiles graph.
  375. Args:
  376. obj (Function/Cell): The function or cell instance need compile.
  377. args (tuple): Function or cell input arguments.
  378. phase (str): The name of compile phase. Default: 'predict'.
  379. do_convert (bool): When set to True, convert ME graph to GE graph after compiling graph.
  380. auto_parallel_mode: When set to True, use auto parallel mode to compile graph.
  381. Return:
  382. Str, the full phase of the cell.
  383. Bool, if the graph has been compiled before, return False, else return True.
  384. """
  385. args_names, args_list = _generate_pip_args(obj, *args)
  386. dic = dict(zip(args_names, args_list))
  387. key = generate_key(phase, dic)
  388. obj.phase_prefix = str(key[1])
  389. if 'export' in phase:
  390. phase = phase + '.' + obj.phase_prefix + '.' + str(obj.create_time)
  391. else:
  392. phase = obj.phase_prefix + phase + '.' + str(obj.create_time)
  393. if phase in self.compile_cache.keys():
  394. logger.debug("%r graph has existed.", phase)
  395. return phase, False
  396. obj.check_names()
  397. _check_full_batch()
  398. self._set_dataset_mode(args_list)
  399. is_sink_mode = args and isinstance(args[0], Tensor) and args[0].virtual_flag
  400. if auto_parallel_mode and _need_to_full() and not is_sink_mode and obj.auto_parallel_compile_and_run():
  401. args_full = _to_full_tensor(args, _get_device_num(), _get_global_rank())
  402. _, args_list = _generate_pip_args(obj, *args_full)
  403. enable_debug_runtime = context.get_context("enable_debug_runtime")
  404. enable_ge = context.get_context("enable_ge")
  405. use_vm = not enable_ge or (enable_debug_runtime and context.get_context("mode") == context.PYNATIVE_MODE)
  406. result = self._executor.compile(obj, args_list, phase, use_vm)
  407. self.compile_cache[phase] = phase
  408. if not result:
  409. raise RuntimeError("Executor compile failed.")
  410. graph = self._executor.get_func_graph(phase)
  411. if graph is None:
  412. logger.error("%r graph compile failed.", phase)
  413. self._auto_parallel_process(obj, phase, is_sink_mode, auto_parallel_mode, *args)
  414. if not do_convert:
  415. return phase, True
  416. # the following GE init process is not needed when use vm or ms backend
  417. if enable_ge:
  418. self._build_data_graph(obj, phase)
  419. if "export" not in phase:
  420. init_phase = "init_subgraph" + "." + str(obj.create_time)
  421. _exec_init_graph(obj, init_phase)
  422. elif not enable_ge and "export" in phase:
  423. self._build_data_graph(obj, phase)
  424. elif BROADCAST_PHASE not in phase and _get_parameter_broadcast():
  425. _parameter_broadcast(obj, auto_parallel_mode)
  426. return phase, True
  427. def _auto_parallel_process(self, obj, phase, is_sink_mode, auto_parallel_mode, *args):
  428. """compile graph in auto parallel mode."""
  429. if not auto_parallel_mode:
  430. replace = obj.init_parameters_data(auto_parallel_mode=auto_parallel_mode)
  431. self._updata_param_node_default_input(phase, replace)
  432. return
  433. obj.parameter_layout_dict = self._executor.get_parameter_layout(phase)
  434. if _get_pipeline_stages() > 1:
  435. obj.parallel_parameter_name_list = self._executor.get_parallel_parameter_name_list(phase)
  436. obj.remove_redundant_parameters()
  437. replace = obj.init_parameters_data(auto_parallel_mode=True)
  438. if not context.get_context("enable_debug_runtime") or context.get_context("enable_ge"):
  439. obj.load_parameter_slice(None)
  440. self._updata_param_node_default_input(phase, replace)
  441. # set parallel inputs in sink mode
  442. if is_sink_mode:
  443. obj.set_parallel_input_with_inputs(*args)
  444. def _updata_param_node_default_input(self, phase, replace):
  445. new_param = {x.name: replace[x] for x in replace if id(x) != id(replace[x])}
  446. return self._executor.updata_param_node_default_input(phase, new_param)
  447. def _get_shard_strategy(self, obj):
  448. real_phase = obj.phase_prefix + obj.phase + '.' + str(obj.create_time)
  449. return self._executor.get_strategy(real_phase)
  450. def _get_num_parallel_ops(self, obj):
  451. real_phase = obj.phase_prefix + obj.phase + '.' + str(obj.create_time)
  452. return self._executor.get_num_parallel_ops(real_phase)
  453. def _get_allreduce_fusion(self, obj):
  454. real_phase = obj.phase_prefix + obj.phase + '.' + str(obj.create_time)
  455. return self._executor.get_allreduce_fusion(real_phase)
  456. def has_compiled(self, phase='predict'):
  457. """
  458. Specify whether have been compiled.
  459. Args:
  460. phase (str): The phase name. Default: 'predict'.
  461. Returns:
  462. bool, specifies whether the specific graph has been compiled.
  463. """
  464. return self._executor.has_compiled(phase)
  465. def __call__(self, obj, *args, phase='predict'):
  466. if context.get_context("precompile_only") or _is_role_pserver():
  467. return None
  468. return self.run(obj, *args, phase=phase)
  469. @_wrap_func
  470. def _exec_pip(self, obj, *args, phase=''):
  471. """Execute the generated pipeline."""
  472. fn = obj.construct
  473. converted, arguments_dict, parse_method = _convert_function_arguments(fn, *args)
  474. if not converted:
  475. raise RuntimeError('Process method parameter is failure')
  476. args_list = tuple(arguments_dict.values())
  477. obj.__parse_method__ = parse_method
  478. return self._executor(args_list, phase)
  479. def run(self, obj, *args, phase='predict'):
  480. """
  481. Run the specific graph.
  482. Args:
  483. phase (str): The phase name. Default: 'predict'.
  484. Returns:
  485. Tensor/Tuple, return execute result.
  486. """
  487. if phase == 'save':
  488. return self._executor((), phase + '.' + str(obj.create_time))
  489. phase_real = obj.phase_prefix + phase + '.' + str(obj.create_time)
  490. if self.has_compiled(phase_real):
  491. return self._exec_pip(obj, *args, phase=phase_real)
  492. raise KeyError('{} graph is not exist.'.format(phase_real))
  493. def del_net_res(self, net_id):
  494. self._executor.del_net_res(net_id)
  495. def _get_func_graph_proto(self, obj, exec_id, ir_type="onnx_ir", use_prefix=False):
  496. """Get graph proto from pipeline."""
  497. if use_prefix:
  498. exec_id = obj.phase_prefix + exec_id
  499. if self._executor.has_compiled(exec_id) is False:
  500. return None
  501. return self._executor.get_func_graph_proto(exec_id, ir_type)
  502. def export(self, file_name, graph_id):
  503. """
  504. Export graph.
  505. Args:
  506. file_name (str): File name of model to export
  507. graph_id (str): id of graph to be exported
  508. """
  509. from .._c_expression import export_graph
  510. export_graph(file_name, 'AIR', graph_id)
  511. def fetch_info_for_quant_export(self, exec_id):
  512. """Get graph proto from pipeline."""
  513. if self._executor.has_compiled(exec_id) is False:
  514. return None
  515. return self._executor.fetch_info_for_quant_export(exec_id)
  516. _executor = _Executor()
  517. _pynative_exec = _PynativeExecutor()
  518. __all__ = ['ms_function']