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.

_utils.py 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Utils of auto parallel"""
  16. import numpy as np
  17. from mindspore import context, log as logger
  18. from mindspore.context import ParallelMode
  19. from mindspore._c_expression import reset_op_id
  20. from mindspore.common.tensor import Tensor
  21. from mindspore.common.dtype import dtype_to_nptype
  22. from mindspore.common import dtype as mstype
  23. from mindspore.communication.management import get_group_size, get_rank
  24. from mindspore.parallel._auto_parallel_context import auto_parallel_context
  25. from mindspore.common.seed import get_seed
  26. def _get_parallel_mode():
  27. """Get parallel mode."""
  28. return auto_parallel_context().get_parallel_mode()
  29. def _is_in_auto_parallel_mode():
  30. return _get_parallel_mode() in [ParallelMode.SEMI_AUTO_PARALLEL, ParallelMode.AUTO_PARALLEL]
  31. def _get_full_batch():
  32. """Get whether to use full_batch."""
  33. return auto_parallel_context().get_full_batch()
  34. def _get_pipeline_stages():
  35. """Get pipeline stages"""
  36. return auto_parallel_context().get_pipeline_stages()
  37. def _check_task_sink_envs():
  38. """
  39. Check whether task_sink environment variables have been exported or not.
  40. return True if task_sink environment variables have been exported, False otherwise.
  41. """
  42. import os
  43. task_sink = os.getenv("SINGLE_OP_MODE")
  44. if task_sink:
  45. try:
  46. if int(task_sink) == 1:
  47. return False
  48. except ValueError:
  49. return True
  50. return True
  51. def _check_full_batch():
  52. """
  53. full_batch could only be used under semi_auto_parallel or auto_parallel, check it.
  54. Raises:
  55. RuntimeError: Using full_batch under neither semi_auto_parallel nor auto_parallel.
  56. """
  57. parallel_mode = _get_parallel_mode()
  58. full_batch = _get_full_batch()
  59. if ((parallel_mode not in ("semi_auto_parallel", "auto_parallel")) and full_batch):
  60. raise RuntimeError("full_batch could only be used under semi_auto_parallel or auto_parallel.")
  61. def _need_to_full():
  62. """Check whether to convert input to full shape or tensor."""
  63. if _get_parallel_mode() not in ("semi_auto_parallel", "auto_parallel"):
  64. return False
  65. dataset_strategy = context.get_auto_parallel_context("dataset_strategy")
  66. if dataset_strategy and dataset_strategy not in ("data_parallel", "full_batch"):
  67. return True
  68. return not _get_full_batch()
  69. def _to_full_shapes(shapes, device_num):
  70. """Expanding batch dimension according to device_num, adapt to mindspore minddata graph solution."""
  71. new_shapes = []
  72. dataset_strategy = ()
  73. if context.get_auto_parallel_context("dataset_strategy") not in ("data_parallel", "full_batch"):
  74. dataset_strategy = context.get_auto_parallel_context("dataset_strategy")
  75. if dataset_strategy:
  76. if len(shapes) != len(dataset_strategy):
  77. raise ValueError("The input shapes size {} is not equal to "
  78. "dataset strategy size {}".format(len(shapes), len(dataset_strategy)))
  79. for index, shape in enumerate(shapes):
  80. if len(shape) != len(dataset_strategy[index]):
  81. raise ValueError("The input shapes item size {} is not equal to "
  82. "dataset strategy item size {}".format(len(shape), len(dataset_strategy[index])))
  83. new_shape = ()
  84. for i, item in enumerate(shape):
  85. new_shape += (item * dataset_strategy[index][i],)
  86. new_shapes.append(new_shape)
  87. return new_shapes
  88. for shape in shapes:
  89. new_shape = ()
  90. for i, item in enumerate(shape):
  91. if i == 0:
  92. new_shape += (item * device_num,)
  93. else:
  94. new_shape += (item,)
  95. new_shapes.append(new_shape)
  96. return new_shapes
  97. def _to_full_tensor(elem, global_device_num, global_rank, scaling_sens=None):
  98. """Convert numpy to tensor, expanding batch dimension according to device_num, adapt to feed the data
  99. from host solution.
  100. """
  101. lst = []
  102. device_num = global_device_num // _get_pipeline_stages()
  103. stage_rank = global_rank % device_num
  104. if not isinstance(elem, (tuple, list)):
  105. elem = [elem]
  106. if stage_rank >= device_num:
  107. raise ValueError("The global rank must be smaller than device number, the global rank is {}, "
  108. "the device num is {}".format(stage_rank, device_num))
  109. dataset_strategy = ()
  110. if context.get_auto_parallel_context("dataset_strategy") not in ("data_parallel", "full_batch"):
  111. dataset_strategy = context.get_auto_parallel_context("dataset_strategy")
  112. if elem and dataset_strategy:
  113. if len(elem) != len(dataset_strategy):
  114. raise ValueError("The input size {} is not equal to "
  115. "dataset strategy size {}".format(len(elem), len(dataset_strategy)))
  116. for index, data in enumerate(elem):
  117. if isinstance(data, np.ndarray):
  118. data = Tensor(data)
  119. if not isinstance(data, Tensor):
  120. raise ValueError("elements in tensors must be Tensor")
  121. shape_ = data.shape
  122. type_ = data.dtype
  123. new_shape = ()
  124. if not dataset_strategy:
  125. batchsize_per_device = 1
  126. for i, item in enumerate(shape_):
  127. if i == 0:
  128. new_shape += (item * device_num,)
  129. batchsize_per_device = item
  130. else:
  131. new_shape += (item,)
  132. new_tensor_numpy = np.zeros(new_shape, dtype_to_nptype(type_))
  133. start = stage_rank * batchsize_per_device
  134. new_tensor_numpy[start: start + batchsize_per_device] = data.asnumpy()
  135. else:
  136. if len(shape_) != len(dataset_strategy[index]):
  137. raise ValueError("The input shapes item size {} is not equal to "
  138. "dataset strategy item size {}".format(len(shape_), len(dataset_strategy[index])))
  139. slice_index = ()
  140. for i, item in enumerate(shape_):
  141. new_shape += (item * dataset_strategy[index][i],)
  142. start = (stage_rank % dataset_strategy[index][i]) * item
  143. end = (stage_rank % dataset_strategy[index][i] + 1) * item
  144. s = slice(start, end, 1)
  145. slice_index += (s,)
  146. new_tensor_numpy = np.zeros(new_shape, dtype_to_nptype(type_))
  147. new_tensor_numpy[slice_index] = data.asnumpy()
  148. new_tensor = Tensor(new_tensor_numpy)
  149. lst.append(new_tensor)
  150. if scaling_sens:
  151. lst.append(Tensor(scaling_sens, mstype.float32))
  152. return tuple(lst)
  153. def _get_gradients_mean():
  154. """Get if using gradients_mean."""
  155. return auto_parallel_context().get_gradients_mean()
  156. def _get_device_num():
  157. """Get the device num."""
  158. parallel_mode = auto_parallel_context().get_parallel_mode()
  159. if parallel_mode == "stand_alone":
  160. device_num = 1
  161. return device_num
  162. if auto_parallel_context().get_device_num_is_set() is False:
  163. device_num = get_group_size()
  164. else:
  165. device_num = auto_parallel_context().get_device_num()
  166. return device_num
  167. def _get_global_rank():
  168. """Get the global rank."""
  169. parallel_mode = auto_parallel_context().get_parallel_mode()
  170. if parallel_mode == "stand_alone":
  171. global_rank = 0
  172. return global_rank
  173. if auto_parallel_context().get_global_rank_is_set() is False:
  174. global_rank = get_rank()
  175. else:
  176. global_rank = auto_parallel_context().get_global_rank()
  177. return global_rank
  178. def _get_parameter_broadcast():
  179. """Get the parameter broadcast."""
  180. parallel_mode = auto_parallel_context().get_parallel_mode()
  181. parameter_broadcast = auto_parallel_context().get_parameter_broadcast()
  182. if parallel_mode in ("data_parallel", "hybrid_parallel") and parameter_broadcast is False and get_seed() is None:
  183. logger.warning("You are suggested to use mindspore.context.set_auto_parallel_context(parameter_broadcast=True)"
  184. " or mindspore.common.set_seed() to share parameters among multi-devices.")
  185. return parameter_broadcast
  186. def _get_enable_parallel_optimizer():
  187. """Get if using parallel optimizer."""
  188. return auto_parallel_context().get_enable_parallel_optimizer()
  189. def _device_number_check(parallel_mode, device_number):
  190. """
  191. Check device num.
  192. Args:
  193. parallel_mode (str): The parallel mode.
  194. device_number (int): The device number.
  195. """
  196. if parallel_mode == "stand_alone" and device_number != 1:
  197. raise ValueError("If parallel_mode is stand_alone, device_number must be 1, "
  198. "device_number: {0}, parallel_mode:{1}".format(device_number, parallel_mode))
  199. def _parameter_broadcast_check(parallel_mode, parameter_broadcast):
  200. """
  201. Check parameter broadcast.
  202. Note:
  203. If parallel mode is semi_auto_parallel or auto_parallel, parameter broadcast is not supported. Using the same
  204. random seed to make sure parameters on multiple devices are the same.
  205. Args:
  206. parallel_mode (str): The parallel mode.
  207. parameter_broadcast (bool): The parameter broadcast.
  208. Raises:
  209. ValueError: If parameter is broadcasted
  210. but the parallel mode is "stand_alone" or "semi_auto_parallel" or "auto_parallel").
  211. """
  212. if parameter_broadcast is True and parallel_mode in ("stand_alone", "semi_auto_parallel", "auto_parallel"):
  213. raise ValueError("stand_alone, semi_auto_parallel and auto_parallel "
  214. "do not support parameter broadcast, parallel_mode: {0}, parameter_broadcast:{1}"
  215. .format(parallel_mode, parameter_broadcast))
  216. def _get_python_op(op_name, op_path, instance_name, arglist):
  217. """Get python operator."""
  218. module = __import__(op_path, fromlist=["None"])
  219. cls = getattr(module, op_name)
  220. if op_path != "mindspore.ops.functional":
  221. op = cls(*arglist)
  222. else:
  223. op = cls
  224. op.set_prim_instance_name(instance_name)
  225. return op
  226. def _reset_op_id():
  227. """Reset op id."""
  228. reset_op_id()
  229. def _parallel_predict_check():
  230. """validate parallel model prediction"""
  231. if _get_parallel_mode() in (ParallelMode.SEMI_AUTO_PARALLEL, ParallelMode.AUTO_PARALLEL):
  232. if not context.get_auto_parallel_context("full_batch"):
  233. raise RuntimeError('Model prediction only supports full batch dataset. Please set "full_batch" with True.')
  234. def _check_similar_layout(tensor_layout1, tensor_layout2):
  235. """check if two tensor layouts are same"""
  236. if tensor_layout1[1] != tensor_layout2[1]:
  237. return False
  238. for i in tensor_layout1[1]:
  239. if i == -1:
  240. continue
  241. if tensor_layout1[0][-1-i] != tensor_layout2[0][-1-i]:
  242. return False
  243. return True
  244. def _check_same_layout(tensor_layout1, tensor_layout2):
  245. """check if two tensor layouts are same"""
  246. return tensor_layout1[0] == tensor_layout2[0] and tensor_layout1[1] == tensor_layout2[1]
  247. def _remove_repeated_slices(tensor_layout):
  248. """generate unrepeated tensor layout"""
  249. import copy
  250. new_tensor_layout = copy.deepcopy(tensor_layout)
  251. dev_mat = tensor_layout[0][:]
  252. tensor_map = tensor_layout[1]
  253. for dim in range(len(dev_mat)):
  254. if dim not in tensor_map:
  255. dev_mat[-1-dim] = 1
  256. new_tensor_layout[0] = dev_mat
  257. return new_tensor_layout
  258. def _infer_rank_list(train_map, predict_map=None):
  259. """infer checkpoint slices to be loaded"""
  260. ret = {}
  261. if _get_pipeline_stages() > 1:
  262. local_rank = int(_get_global_rank() % (_get_device_num() / _get_pipeline_stages()))
  263. else:
  264. local_rank = _get_global_rank()
  265. for param_name in train_map:
  266. train_layout = train_map[param_name]
  267. train_dev_mat = train_layout[0]
  268. dev_num = np.array(train_dev_mat).prod()
  269. new_train_layout = _remove_repeated_slices(train_layout)
  270. array = np.arange(dev_num).reshape(train_dev_mat)
  271. index = ()
  272. for i in new_train_layout[0]:
  273. if i == 1:
  274. index = index + (0,)
  275. else:
  276. index = index + (slice(None),)
  277. rank_list = array[index].flatten()
  278. if not predict_map:
  279. ret[param_name] = (rank_list, False)
  280. continue
  281. if param_name not in predict_map:
  282. logger.warning("predict_map does not contain %s", param_name)
  283. continue
  284. predict_layout = predict_map[param_name]
  285. dev_num = np.array(predict_layout[0]).prod()
  286. # optimization pass
  287. if _check_same_layout(train_layout, predict_layout):
  288. ret[param_name] = ([local_rank], True)
  289. continue
  290. if _check_similar_layout(train_layout, predict_layout):
  291. if len(rank_list) == 1:
  292. ret[param_name] = (rank_list, True)
  293. elif len(rank_list) == dev_num:
  294. ret[param_name] = ([rank_list[local_rank]], True)
  295. else:
  296. ret[param_name] = (rank_list, False)
  297. else:
  298. ret[param_name] = (rank_list, False)
  299. return ret