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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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_full_batch():
  38. """
  39. full_batch could only be used under semi_auto_parallel or auto_parallel, check it.
  40. Raises:
  41. RuntimeError: Using full_batch under neither semi_auto_parallel nor auto_parallel.
  42. """
  43. parallel_mode = _get_parallel_mode()
  44. full_batch = _get_full_batch()
  45. if ((parallel_mode not in ("semi_auto_parallel", "auto_parallel")) and full_batch):
  46. raise RuntimeError("full_batch could only be used under semi_auto_parallel or auto_parallel.")
  47. def _need_to_full():
  48. """Check whether to convert input to full shape or tensor."""
  49. parallel_mode = _get_parallel_mode()
  50. full_batch = _get_full_batch()
  51. need = ((parallel_mode in ("semi_auto_parallel", "auto_parallel"))
  52. and (not full_batch))
  53. return need
  54. def _to_full_shapes(shapes, device_num):
  55. """Expanding batch dimension according to device_num, adapt to mindspore minddata graph solution."""
  56. new_shapes = []
  57. for shape in shapes:
  58. new_shape = ()
  59. for i, item in enumerate(shape):
  60. if i == 0:
  61. new_shape += (item * device_num,)
  62. else:
  63. new_shape += (item,)
  64. new_shapes.append(new_shape)
  65. return new_shapes
  66. def _to_full_tensor(elem, device_num, global_rank, scaling_sens=None):
  67. """Convert numpy to tensor, expanding batch dimension according to device_num, adapt to feed the data
  68. from host solution."""
  69. lst = []
  70. if not isinstance(elem, (tuple, list)):
  71. elem = [elem]
  72. if global_rank >= device_num:
  73. raise ValueError("The global rank must be smaller than device number, the global rank is {}, "
  74. "the device num is {}".format(global_rank, device_num))
  75. for data in elem:
  76. if isinstance(data, np.ndarray):
  77. data = Tensor(data)
  78. if not isinstance(data, Tensor):
  79. raise ValueError("elements in tensors must be Tensor")
  80. shape_ = data.shape
  81. type_ = data.dtype
  82. new_shape = ()
  83. batchsize_per_device = 1
  84. for i, item in enumerate(shape_):
  85. if i == 0:
  86. new_shape += (item * device_num,)
  87. batchsize_per_device = item
  88. else:
  89. new_shape += (item,)
  90. new_tensor_numpy = np.zeros(new_shape, dtype_to_nptype(type_))
  91. start = global_rank * batchsize_per_device
  92. new_tensor_numpy[start: start + batchsize_per_device] = data.asnumpy()
  93. new_tensor = Tensor(new_tensor_numpy)
  94. lst.append(new_tensor)
  95. if scaling_sens:
  96. lst.append(Tensor(scaling_sens, mstype.float32))
  97. return tuple(lst)
  98. def _get_gradients_mean():
  99. """Get if using gradients_mean."""
  100. return auto_parallel_context().get_gradients_mean()
  101. def _get_device_num():
  102. """Get the device num."""
  103. parallel_mode = auto_parallel_context().get_parallel_mode()
  104. if parallel_mode == "stand_alone":
  105. device_num = 1
  106. return device_num
  107. if auto_parallel_context().get_device_num_is_set() is False:
  108. device_num = get_group_size()
  109. else:
  110. device_num = auto_parallel_context().get_device_num()
  111. return device_num
  112. def _get_global_rank():
  113. """Get the global rank."""
  114. parallel_mode = auto_parallel_context().get_parallel_mode()
  115. if parallel_mode == "stand_alone":
  116. global_rank = 0
  117. return global_rank
  118. if auto_parallel_context().get_global_rank_is_set() is False:
  119. global_rank = get_rank()
  120. else:
  121. global_rank = auto_parallel_context().get_global_rank()
  122. return global_rank
  123. def _get_parameter_broadcast():
  124. """Get the parameter broadcast."""
  125. parallel_mode = auto_parallel_context().get_parallel_mode()
  126. parameter_broadcast = auto_parallel_context().get_parameter_broadcast()
  127. if parallel_mode in ("data_parallel", "hybrid_parallel") and parameter_broadcast is False and get_seed() is None:
  128. logger.warning("You are suggested to use mindspore.context.set_auto_parallel_context(parameter_broadcast=True)"
  129. " or mindspore.common.set_seed() to share parameters among multi-devices.")
  130. return parameter_broadcast
  131. def _device_number_check(parallel_mode, device_number):
  132. """
  133. Check device num.
  134. Args:
  135. parallel_mode (str): The parallel mode.
  136. device_number (int): The device number.
  137. """
  138. if parallel_mode == "stand_alone" and device_number != 1:
  139. raise ValueError("If parallel_mode is stand_alone, device_number must be 1, "
  140. "device_number: {0}, parallel_mode:{1}".format(device_number, parallel_mode))
  141. def _parameter_broadcast_check(parallel_mode, parameter_broadcast):
  142. """
  143. Check parameter broadcast.
  144. Note:
  145. If parallel mode is semi_auto_parallel or auto_parallel, parameter broadcast is not supported. Using the same
  146. random seed to make sure parameters on multiple devices are the same.
  147. Args:
  148. parallel_mode (str): The parallel mode.
  149. parameter_broadcast (bool): The parameter broadcast.
  150. Raises:
  151. ValueError: If parameter is broadcasted
  152. but the parallel mode is "stand_alone" or "semi_auto_parallel" or "auto_parallel").
  153. """
  154. if parameter_broadcast is True and parallel_mode in ("stand_alone", "semi_auto_parallel", "auto_parallel"):
  155. raise ValueError("stand_alone, semi_auto_parallel and auto_parallel "
  156. "do not support parameter broadcast, parallel_mode: {0}, parameter_broadcast:{1}"
  157. .format(parallel_mode, parameter_broadcast))
  158. def _get_python_op(op_name, op_path, instance_name, arglist):
  159. """Get python operator."""
  160. module = __import__(op_path, fromlist=["None"])
  161. cls = getattr(module, op_name)
  162. if op_path != "mindspore.ops.functional":
  163. op = cls(*arglist)
  164. else:
  165. op = cls
  166. op.set_prim_instance_name(instance_name)
  167. return op
  168. def _reset_op_id():
  169. """Reset op id."""
  170. reset_op_id()
  171. def _parallel_predict_check():
  172. """validate parallel model prediction"""
  173. if _get_parallel_mode() in (ParallelMode.SEMI_AUTO_PARALLEL, ParallelMode.AUTO_PARALLEL):
  174. if not context.get_auto_parallel_context("full_batch"):
  175. raise RuntimeError('Model prediction only supports full batch dataset. Please set "full_batch" with True.')
  176. if context.get_auto_parallel_context("enable_parallel_optimizer"):
  177. raise RuntimeError('Model prediction does not support parallel optimizer. Please set'
  178. '"enable_parallel_optimizer" with False.')
  179. def _check_similar_layout(tensor_layout1, tensor_layout2):
  180. """check if two tensor layouts are same"""
  181. if tensor_layout1[1] != tensor_layout2[1]:
  182. return False
  183. for i in tensor_layout1[1]:
  184. if i == -1:
  185. continue
  186. if tensor_layout1[0][-1-i] != tensor_layout2[0][-1-i]:
  187. return False
  188. return True
  189. def _check_same_layout(tensor_layout1, tensor_layout2):
  190. """check if two tensor layouts are same"""
  191. return tensor_layout1[0] == tensor_layout2[0] and tensor_layout1[1] == tensor_layout2[1]
  192. def _remove_repeated_slices(tensor_layout):
  193. """generate unrepeated tensor layout"""
  194. import copy
  195. new_tensor_layout = copy.deepcopy(tensor_layout)
  196. dev_mat = tensor_layout[0][:]
  197. tensor_map = tensor_layout[1]
  198. for dim in range(len(dev_mat)):
  199. if dim not in tensor_map:
  200. dev_mat[-1-dim] = 1
  201. new_tensor_layout[0] = dev_mat
  202. return new_tensor_layout
  203. def _infer_rank_list(train_map, predict_map=None):
  204. """infer checkpoint slices to be loaded"""
  205. ret = {}
  206. if _get_pipeline_stages() > 1:
  207. local_rank = int(_get_global_rank() % (_get_device_num() / _get_pipeline_stages()))
  208. else:
  209. local_rank = _get_global_rank()
  210. for param_name in train_map:
  211. train_layout = train_map[param_name]
  212. train_dev_mat = train_layout[0]
  213. dev_num = np.array(train_dev_mat).prod()
  214. new_train_layout = _remove_repeated_slices(train_layout)
  215. array = np.arange(dev_num).reshape(train_dev_mat)
  216. index = ()
  217. for i in new_train_layout[0]:
  218. if i == 1:
  219. index = index + (0,)
  220. else:
  221. index = index + (slice(None),)
  222. rank_list = array[index].flatten()
  223. if not predict_map:
  224. ret[param_name] = (rank_list, False)
  225. continue
  226. if param_name not in predict_map:
  227. logger.warning("predict_map does not contain %s", param_name)
  228. continue
  229. predict_layout = predict_map[param_name]
  230. dev_num = np.array(predict_layout[0]).prod()
  231. # optimization pass
  232. if _check_same_layout(train_layout, predict_layout):
  233. ret[param_name] = ([local_rank], True)
  234. continue
  235. if _check_similar_layout(train_layout, predict_layout):
  236. if len(rank_list) == 1:
  237. ret[param_name] = (rank_list, True)
  238. elif len(rank_list) == dev_num:
  239. ret[param_name] = ([rank_list[local_rank]], True)
  240. else:
  241. ret[param_name] = (rank_list, False)
  242. else:
  243. ret[param_name] = (rank_list, False)
  244. return ret