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