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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. from collections import OrderedDict
  20. from functools import wraps
  21. from mindspore import context
  22. from mindspore import log as logger
  23. from mindspore.parallel._utils import _get_parallel_mode
  24. from .._c_expression import generate_key, Executor_, Tensor, MetaTensor
  25. from .._c_expression import verify_inputs_signature, init_exec_dataset, _set_dataset_mode_config, init_backend
  26. from .tensor import Tensor as MsTensor
  27. # store ms_function class compiled pipeline cache
  28. ms_compile_cache = {}
  29. def _convert_function_arguments(fn, *args):
  30. """
  31. Process the fn default parameters.
  32. Args:
  33. fn (Function): The function to be parsed.
  34. args (tuple): The parameters of the function.
  35. """
  36. arguments_dict = OrderedDict()
  37. parse_method = None
  38. if isinstance(fn, (types.FunctionType, types.MethodType)):
  39. parse_method = fn.__name__
  40. index = 0
  41. for value in args:
  42. arguments_dict[f'arg{index}'] = value
  43. index = index + 1
  44. logger.debug("fn(%r) full parameters dict is: %r", fn, arguments_dict)
  45. converted = True
  46. else:
  47. logger.warning("Find error: fn isn't function or method")
  48. converted = False
  49. return converted, arguments_dict, parse_method
  50. def _wrap_func(fn):
  51. """
  52. Wrapper function, convert return data to tensor or tuple of tensor.
  53. Args:
  54. fn (Function): The function need be wrapped.
  55. Returns:
  56. Function, a new function with return suitable format data.
  57. """
  58. @wraps(fn)
  59. def wrapper(*arg, **kwargs):
  60. results = fn(*arg, **kwargs)
  61. def _convert_data(data):
  62. if isinstance(data, Tensor) and not isinstance(data, MsTensor):
  63. return MsTensor(data)
  64. return data
  65. if isinstance(results, tuple):
  66. return tuple(_convert_data(x) for x in results)
  67. if isinstance(results, list):
  68. return list(_convert_data(x) for x in results)
  69. return _convert_data(results)
  70. return wrapper
  71. def _exec_init_graph(obj, init_phase):
  72. """Execute the parameter initializer graph."""
  73. inst_executor = Executor_.get_instance()
  74. exec_init_graph = False
  75. for param in obj.get_parameters():
  76. if not param.is_init:
  77. param.is_init = True
  78. exec_init_graph = True
  79. if exec_init_graph:
  80. inst_executor.run_init_graph(obj.parameters_dict(), init_phase)
  81. class _MindSporeFunction:
  82. """
  83. Represents a function compiled by mind expression.
  84. _MindSporeFunction will compile the original function for every combination
  85. of argument types and shapes it is given (as well as their values, optionally).
  86. Args:
  87. fn (Function): The root function to compile.
  88. input_signature (Function): User defines signature to verify input.
  89. obj (Object): If function is a method, obj is the owner of function,
  90. else, obj is none.
  91. """
  92. def __init__(self, fn, input_signature=None, obj=None):
  93. self.fn = fn
  94. self.save_graphs = context.get_context("save_graphs")
  95. self.save_graphs_path = context.get_context("save_graphs_path")
  96. self.input_signature = input_signature
  97. self.obj = None
  98. self.identify_obj = None
  99. if hasattr(obj, fn.__name__):
  100. self.obj = obj
  101. elif obj is not None:
  102. self.identify_obj = obj
  103. self._executor = Executor_.get_instance()
  104. def build_data_init_graph(self, graph_name):
  105. """Build GE data graph and init graph for the given graph name."""
  106. if self.obj is None:
  107. logger.warning("Make sure parameter should not be used in function")
  108. para_dict = OrderedDict()
  109. self._executor.build_data_graph(para_dict, graph_name)
  110. return
  111. self._executor.build_data_graph(self.obj.parameters_dict(), graph_name, self.obj.parameters_broadcast_dict())
  112. init_phase = "init_subgraph" + graph_name[graph_name.find("."):]
  113. _exec_init_graph(self.obj, init_phase)
  114. def compile(self, arguments_dict, method_name):
  115. """Returns pipline for the given args."""
  116. args_list = tuple(arguments_dict.values())
  117. arg_names = tuple(arguments_dict.keys())
  118. # remove first self parameter when fn is a method
  119. if self.obj is not None:
  120. args_list = args_list[1:]
  121. arg_names = arg_names[1:]
  122. # verify the signature for both function and method
  123. if self.input_signature is not None:
  124. signatures = []
  125. for sig_spec in self.input_signature:
  126. if not isinstance(sig_spec, MetaTensor):
  127. raise TypeError("Input_signature is not MetaTensor")
  128. signatures.append(sig_spec)
  129. is_valid_input = verify_inputs_signature(signatures, args_list)
  130. if not is_valid_input:
  131. raise ValueError("Inputs is incompatible with input signature!")
  132. dic = dict(zip(arg_names, args_list))
  133. generate_name = self.fn.__module__ + "." + self.fn.__name__
  134. self.fn.__parse_method__ = method_name
  135. # replace key with obj info and object ext info when fn is a method
  136. if self.obj is not None:
  137. self.obj.__parse_method__ = method_name
  138. generate_name = self.obj.__module__ + "." + str(self.obj.create_time)
  139. if self.identify_obj is not None:
  140. generate_name = generate_name + str(id(self.identify_obj))
  141. key = generate_key(generate_name, dic)
  142. phase = str(key[1]) + generate_name
  143. if key not in ms_compile_cache.keys():
  144. is_compile = False
  145. if self.obj is None:
  146. is_compile = self._executor.compile(self.fn, args_list, phase, True)
  147. else:
  148. is_compile = self._executor.compile(self.obj, args_list, phase, True)
  149. if not is_compile:
  150. raise RuntimeError("Executor compile failed.")
  151. if context.get_context("enable_ge"):
  152. self.build_data_init_graph(phase)
  153. # since function can be redefined, we only cache class method pipeline
  154. if self.obj is not None or self.identify_obj is not None:
  155. ms_compile_cache[key] = phase
  156. return phase
  157. return ms_compile_cache[key]
  158. @_wrap_func
  159. def __call__(self, *args):
  160. init_backend()
  161. converted, arguments_dict, parse_method = _convert_function_arguments(self.fn, *args)
  162. if not converted:
  163. raise RuntimeError('Process function parameter is failure')
  164. args_list = tuple(arguments_dict.values())
  165. if self.obj is not None:
  166. args_list = args_list[1:]
  167. phase = self.compile(arguments_dict, parse_method)
  168. if context.get_context("precompile_only"):
  169. return None
  170. return self._executor(args_list, phase)
  171. def ms_function(fn=None, obj=None, input_signature=None):
  172. """
  173. Creates a callable MindSpore graph from a python function.
  174. This allows the MindSpore runtime to apply optimizations based on graph.
  175. Args:
  176. fn (Function): The Python function that will be run as a graph. Default: None.
  177. obj (Object): The Python Object that provide information for identify compiled function. Default: None.
  178. input_signature (MetaTensor): The MetaTensor to describe the input arguments. The MetaTensor specifies
  179. the shape and dtype of the Tensor and they will be supplied to this function. If input_signature
  180. is specified, every input to `fn` must be a `Tensor`. And the input parameters of `fn` cannot accept
  181. `**kwargs`. The shape and dtype of actual inputs should keep same with input_signature, or TypeError
  182. will be raised. Default: None.
  183. Returns:
  184. Function, if `fn` is not None, returns a callable that will execute the compiled function; If `fn` is None,
  185. returns a decorator and when this decorator invokes with a single `fn` argument, the callable is equal to the
  186. case when `fn` is not None.
  187. Examples:
  188. >>> def tensor_add(x, y):
  189. >>> z = F.tensor_add(x, y)
  190. >>> return z
  191. >>>
  192. >>> @ms_function
  193. >>> def tensor_add_with_dec(x, y):
  194. >>> z = F.tensor_add(x, y)
  195. >>> return z
  196. >>>
  197. >>> @ms_function(input_signature=(MetaTensor(mindspore.float32, (1, 1, 3, 3)),
  198. >>> MetaTensor(mindspore.float32, (1, 1, 3, 3))))
  199. >>> def tensor_add_with_sig(x, y):
  200. >>> z = F.tensor_add(x, y)
  201. >>> return z
  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. >>> tensor_add_graph = ms_function(fn=tensor_add)
  207. >>> out = tensor_add_graph(x, y)
  208. >>> out = tensor_add_with_dec(x, y)
  209. >>> out = tensor_add_with_sig(x, y)
  210. """
  211. def wrap_mindspore(func):
  212. @wraps(func)
  213. def staging_specialize(*args):
  214. process_obj = obj
  215. if args and not isinstance(args[0], MsTensor) and hasattr(args[0], func.__name__):
  216. process_obj = args[0]
  217. args = (x.default_input if hasattr(x, 'default_input') else x for x in args)
  218. return _MindSporeFunction(func, input_signature, process_obj)(*args)
  219. return staging_specialize
  220. if fn is not None:
  221. return wrap_mindspore(fn)
  222. return wrap_mindspore
  223. def _generate_pip_args(obj, *args, method="construct"):
  224. """Generate arguments for pipeline."""
  225. if hasattr(obj, method):
  226. fn = getattr(obj, method)
  227. else:
  228. raise AttributeError('The process method is not exist')
  229. converted, arguments_dict, parse_method = _convert_function_arguments(fn, *args)
  230. if not converted:
  231. raise RuntimeError('Process method parameter is failure')
  232. args_list = tuple(arguments_dict.values())
  233. args_names = tuple(arguments_dict.keys())
  234. obj.__parse_method__ = parse_method
  235. return args_names, args_list
  236. class _Executor:
  237. """
  238. An executor used to compile/manage/run graph.
  239. Including data_graph, train_graph, eval_graph and predict graph.
  240. Returns:
  241. Graph, return the result of pipeline running.
  242. """
  243. def __init__(self):
  244. # create needed graph by lazy mode
  245. self.is_init = False
  246. self._executor = Executor_.get_instance()
  247. self.compile_cache = {}
  248. self.phase_prefix = ""
  249. def init_dataset(self, queue_name, dataset_size, batch_size, dataset_types, dataset_shapes,
  250. input_indexs, phase='dataset'):
  251. """
  252. Initialization interface for calling data subgraph.
  253. Args:
  254. queue_name (str): The name of tdt queue on the device.
  255. dataset_size (int): The size of dataset.
  256. batch_size (int): The size of batch.
  257. dataset_types (list): The output types of element in dataset.
  258. dataset_shapes (list): The output shapes of element in dataset.
  259. input_indexs (list): The index of data with net.
  260. phase (str): The name of phase, e.g., train_dataset/eval_dataset. Default: 'dataset'.
  261. Returns:
  262. bool, specifies whether the data subgraph was initialized successfully.
  263. """
  264. if not init_exec_dataset(queue_name=queue_name,
  265. size=dataset_size,
  266. batch_size=batch_size,
  267. types=dataset_types,
  268. shapes=dataset_shapes,
  269. input_indexs=input_indexs,
  270. phase=phase):
  271. raise RuntimeError("Failure to init and dataset subgraph!")
  272. return True
  273. def _build_data_graph(self, obj, params, phase):
  274. if params is None:
  275. self._executor.build_data_graph(obj.parameters_dict(), phase, obj.parameters_broadcast_dict())
  276. elif isinstance(params, OrderedDict):
  277. self._executor.build_data_graph(params, phase)
  278. else:
  279. raise TypeError('Parameters need OrderedDict type, but got {}'.
  280. format(type(params)))
  281. def compile(self, obj, *args, phase='predict', params=None, do_convert=True):
  282. """
  283. Compiles graph.
  284. Args:
  285. obj (Function/Cell): The function or cell instance need compile.
  286. args (tuple): Function or cell input arguments.
  287. phase (str): The name of compile phase. Default: 'predict'.
  288. params (OrderedDict): The parameters dictionary used for init data graph. Default: None.
  289. do_convert (bool): When set to True, convert ME graph to GE graph after compiling graph.
  290. Return:
  291. Str, the full phase of the cell.
  292. Bool, if the graph has been compiled before, return False, else return True.
  293. """
  294. obj.check_names()
  295. args_names, args_list = _generate_pip_args(obj, *args)
  296. dic = dict(zip(args_names, args_list))
  297. key = generate_key(phase, dic)
  298. self.phase_prefix = str(key[1])
  299. if phase == 'export':
  300. phase = phase + '.' + str(obj.create_time)
  301. else:
  302. phase = self.phase_prefix + phase + '.' + str(obj.create_time)
  303. enable_debug_runtime = context.get_context("enable_debug_runtime")
  304. enable_ge = context.get_context("enable_ge")
  305. use_vm = not enable_ge or (enable_debug_runtime and context.get_context("mode") == context.PYNATIVE_MODE)
  306. if phase in self.compile_cache.keys():
  307. logger.debug("%r graph has existed.", phase)
  308. return phase, False
  309. result = self._executor.compile(obj, args_list, phase, use_vm)
  310. self.compile_cache[phase] = phase
  311. if not result:
  312. raise RuntimeError("Executor compile failed.")
  313. graph = self._executor.get_func_graph(phase)
  314. if graph is None:
  315. logger.error("%r graph compile failed.", phase)
  316. if not do_convert:
  317. return phase, True
  318. if not enable_debug_runtime or enable_ge:
  319. if _get_parallel_mode() in ["auto_parallel", "semi_auto_parallel"]:
  320. obj.parameter_layout_dict = self._executor.get_parameter_layout(phase)
  321. obj.load_parameter_slice(params)
  322. # the following GE init process is not needed when use vm or ms backend
  323. if enable_ge:
  324. # decide whether to sink based on whether the inputs is virtual or not
  325. if args_list and isinstance(args_list[0], Tensor) and args_list[0].virtual_flag:
  326. _set_dataset_mode_config('sink')
  327. else:
  328. _set_dataset_mode_config('normal')
  329. self._build_data_graph(obj, params, phase)
  330. if "export" not in phase:
  331. init_phase = "init_subgraph" + "." + str(obj.create_time)
  332. _exec_init_graph(obj, init_phase)
  333. elif not enable_ge and "export" in phase:
  334. self._build_data_graph(obj, params, phase)
  335. return phase, True
  336. def _get_strategy(self, obj):
  337. real_phase = self.phase_prefix + obj.phase + '.' + str(obj.create_time)
  338. return self._executor.get_strategy(real_phase)
  339. def _get_allreduce_fusion(self, obj):
  340. real_phase = self.phase_prefix + obj.phase + '.' + str(obj.create_time)
  341. return self._executor.get_allreduce_fusion(real_phase)
  342. def has_compiled(self, phase='predict'):
  343. """
  344. Specify whether have been compiled.
  345. Args:
  346. phase (str): The phase name. Default: 'predict'.
  347. Returns:
  348. bool, specifies whether the specific graph has been compiled.
  349. """
  350. return self._executor.has_compiled(phase)
  351. def __call__(self, obj, *args, phase='predict'):
  352. if context.get_context("precompile_only"):
  353. return None
  354. return self.run(obj, *args, phase=phase)
  355. @_wrap_func
  356. def _exec_pip(self, obj, *args, phase=''):
  357. """Execute the generated pipeline."""
  358. fn = obj.construct
  359. converted, arguments_dict, parse_method = _convert_function_arguments(fn, *args)
  360. if not converted:
  361. raise RuntimeError('Process method parameter is failure')
  362. args_list = tuple(arguments_dict.values())
  363. obj.__parse_method__ = parse_method
  364. return self._executor(args_list, phase)
  365. def run(self, obj, *args, phase='predict'):
  366. """
  367. Run the specific graph.
  368. Args:
  369. phase (str): The phase name. Default: 'predict'.
  370. Returns:
  371. Tensor/Tuple, return execute result.
  372. """
  373. if phase == 'save':
  374. return self._executor((), phase + '.' + str(obj.create_time))
  375. phase_real = self.phase_prefix + phase + '.' + str(obj.create_time)
  376. if self.has_compiled(phase_real):
  377. return self._exec_pip(obj, *args, phase=phase_real)
  378. raise KeyError('{} graph is not exist.'.format(phase_real))
  379. def del_net_res(self, net_id):
  380. self._executor.del_net_res(net_id)
  381. def _get_func_graph_proto(self, exec_id, ir_type="onnx_ir", use_prefix=False):
  382. """Get graph proto from pipeline."""
  383. if use_prefix:
  384. exec_id = self.phase_prefix + exec_id
  385. if self._executor.has_compiled(exec_id) is False:
  386. return None
  387. return self._executor.get_func_graph_proto(exec_id, ir_type)
  388. def export(self, net, file_name, file_format='GEIR'):
  389. """
  390. Export graph.
  391. Args:
  392. net (Cell): MindSpore network
  393. file_name (str): File name of model to export
  394. file_format (str): MindSpore currently support 'GEIR' and 'ONNX' format for exported model
  395. """
  396. from .._c_expression import export_graph
  397. phase = 'export' + '.' + str(net.create_time)
  398. export_graph(file_name, file_format, phase)
  399. _executor = _Executor()
  400. __all__ = ['ms_function']