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.

helper.py 8.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import functools
  10. import multiprocessing as mp
  11. from collections import defaultdict
  12. from typing import Callable
  13. from weakref import WeakSet
  14. import numpy as np
  15. from megengine.autodiff.grad_manager import GradManager, get_backwarding_grad_manager
  16. from ..core._imperative_rt.core2 import apply
  17. from ..core.ops.builtin import ParamPackConcat, ParamPackSplit
  18. from ..functional.tensor import copy
  19. from ..tensor import Tensor
  20. from ..utils.deprecation import deprecated_func
  21. from ..utils.future import Future
  22. from . import group as _group
  23. from .functional import _bcast_param, all_reduce_sum, broadcast
  24. from .group import WORLD, Group, group_barrier, is_distributed, override_backend
  25. def param_pack_split(inp: Tensor, offsets: list, shapes: list):
  26. r"""Returns split tensor to tensor list as offsets and shapes described,
  27. only used for ``parampack``.
  28. Args:
  29. inp: input tensor.
  30. offsets: offsets of outputs, length of `2 * n`,
  31. while n is tensor nums you want to split,
  32. format `[begin0, end0, begin1, end1]`.
  33. shapes: tensor shapes of outputs.
  34. Returns:
  35. splitted tensors.
  36. Examples:
  37. .. testcode::
  38. import numpy as np
  39. from megengine import tensor
  40. from megengine.distributed.helper import param_pack_split
  41. a = tensor(np.ones((10,), np.int32))
  42. b, c = param_pack_split(a, [0, 1, 1, 10], [(1,), (3, 3)])
  43. print(b.numpy())
  44. print(c.numpy())
  45. Outputs:
  46. .. testoutput::
  47. [1]
  48. [[1 1 1]
  49. [1 1 1]
  50. [1 1 1]]
  51. """
  52. op = ParamPackSplit()
  53. op.offsets = offsets
  54. op.shapes = [s or (1,) for s in shapes]
  55. outputs = apply(op, inp)
  56. return outputs
  57. def param_pack_concat(inps: list, offsets: Tensor, offsets_val: list):
  58. r"""Returns concated tensor, only used for ``parampack``.
  59. Args:
  60. inps: input tensors.
  61. offsets: device value of offsets.
  62. offsets_val: offsets of inputs, length of `2 * n`,
  63. format `[begin0, end0, begin1, end1]`.
  64. Returns:
  65. concated tensor.
  66. Examples:
  67. .. testcode::
  68. import numpy as np
  69. from megengine import tensor
  70. from megengine.distributed.helper import param_pack_concat
  71. a = tensor(np.ones((1,), np.int32))
  72. b = tensor(np.ones((3, 3), np.int32))
  73. offsets_val = [0, 1, 1, 10]
  74. offsets = tensor(offsets_val, np.int32)
  75. c = param_pack_concat([a, b], offsets, offsets_val)
  76. print(c.numpy())
  77. Outputs:
  78. .. testoutput::
  79. [1 1 1 1 1 1 1 1 1 1]
  80. """
  81. op = ParamPackConcat()
  82. op.offsets = offsets_val
  83. return apply(op, *inps, offsets)[0]
  84. def get_offsets(shapes):
  85. offsets = []
  86. offset = 0
  87. for shape in shapes:
  88. offsets.append(offset)
  89. offset += int(np.prod(shape))
  90. offsets.append(offset)
  91. return offsets
  92. _enable_p2p_cache = None
  93. def _check_enable_p2p():
  94. global _enable_p2p_cache
  95. if _enable_p2p_cache is not None:
  96. return _enable_p2p_cache
  97. cmd = ["nvidia-smi", "topo", "-p2p", "w"]
  98. import subprocess
  99. output = subprocess.run(cmd, stdout=subprocess.PIPE).stdout
  100. if output.count(b"OK") > 1:
  101. _enable_p2p_cache = True
  102. return True
  103. else:
  104. _enable_p2p_cache = False
  105. return False
  106. def pack_allreduce_split(pack_list, shapes, group, reduce_method):
  107. offsets_val = get_offsets(shapes)
  108. offsets = Tensor(offsets_val)
  109. packed_grads = param_pack_concat(pack_list, offsets, offsets_val)
  110. packed_grads = all_reduce_sum(packed_grads, group, group.comp_node)
  111. if reduce_method == "mean":
  112. packed_grads /= group.size
  113. grads = param_pack_split(packed_grads, offsets_val, shapes)
  114. return grads
  115. class TensorFuture(Future):
  116. def device(self):
  117. raise "Sorry, this tensor is not ready"
  118. def numpy(self):
  119. raise "Sorry, this tensor is not ready"
  120. def shape(self):
  121. raise "Sorry, this tensor is not ready"
  122. def dtype(self):
  123. raise "Sorry, this tensor is not ready"
  124. def synchronized(func: Callable):
  125. r"""Decorator. Decorated function will synchronize when finished.
  126. Specifically, we use this to prevent data race during hub.load
  127. """
  128. @functools.wraps(func)
  129. def wrapper(*args, **kwargs):
  130. if not is_distributed():
  131. return func(*args, **kwargs)
  132. ret = func(*args, **kwargs)
  133. group_barrier()
  134. return ret
  135. return wrapper
  136. def _check_device_initialized(device_type: str, rank: int):
  137. try:
  138. test = Tensor(1, device=(device_type + str(rank)))
  139. inited = False
  140. del test
  141. except:
  142. inited = True
  143. errmsg = "The cuda env is set before the forked thread starts. Please do not use any cuda function or variable before forking."
  144. if inited:
  145. raise RuntimeError(errmsg)
  146. get_device_count_by_fork = deprecated_func(
  147. "1.5", "megengine.device", "get_device_count", False
  148. )
  149. def bcast_list_(inps: list, group: Group = WORLD):
  150. r"""Broadcast tensors between given group.
  151. Args:
  152. inps: input tensors.
  153. group: communication group.
  154. """
  155. for inp in inps:
  156. inp._reset(_bcast_param(inp, group))
  157. class AllreduceCallback:
  158. r"""Allreduce Callback with tensor fusion optimization.
  159. Args:
  160. reduce_method: the method to reduce gradiants.
  161. group: communication group.
  162. backend: override distributed backend in allreduce
  163. """
  164. def __init__(self, reduce_method: str, group: Group = WORLD, backend: str = None):
  165. reduce_method = reduce_method.lower()
  166. assert reduce_method in ["sum", "mean"], "reduce_method should be sum or mean"
  167. self._reduce_method = reduce_method
  168. self._group = group
  169. self._marked_gm = WeakSet()
  170. self._param_pack_thd = 10 * 1024 * 1024
  171. self._reset()
  172. if backend is None:
  173. assert _group._sd, "please call init_process_group first"
  174. backend = _group._sd.backend
  175. if backend == "auto":
  176. if group.is_single_machine and not _check_enable_p2p():
  177. backend = "shm"
  178. else:
  179. backend = "nccl"
  180. self._backend = backend
  181. def _reset(self):
  182. self._params = []
  183. self._gradients_dict = dict()
  184. self._futures_dict = dict()
  185. self._packing_list = defaultdict(list)
  186. self._packing_size = defaultdict(int)
  187. self._grad_origin_device = dict()
  188. def _pack(self, dtype):
  189. if len(self._packing_list[dtype]) == 0:
  190. return
  191. grad_list = [self._gradients_dict[p] for p in self._packing_list[dtype]]
  192. shapes = [p._tuple_shape for p in self._packing_list[dtype]]
  193. with override_backend(self._backend):
  194. reduced_grads = pack_allreduce_split(
  195. grad_list, shapes, self._group, self._reduce_method
  196. )
  197. for param, grad in zip(self._packing_list[dtype], reduced_grads):
  198. self._gradients_dict[param] = grad
  199. self._packing_list[dtype] = []
  200. self._packing_size[dtype] = 0
  201. def __call__(self, param, grad):
  202. gm = get_backwarding_grad_manager()
  203. assert isinstance(gm, GradManager)
  204. if gm not in self._marked_gm:
  205. gm._register_after_backward_callback(self._flush)
  206. self._marked_gm.add(gm)
  207. self._params.append(param)
  208. self._futures_dict[param] = TensorFuture(ack=False)
  209. self._gradients_dict[param] = grad
  210. self._grad_origin_device[param] = str(grad.device)
  211. dtype_str = str(np.dtype(param.dtype))
  212. dtype_size = np.dtype(param.dtype).itemsize
  213. self._packing_list[dtype_str].append(param)
  214. self._packing_size[dtype_str] += int(np.prod(param._tuple_shape)) * dtype_size
  215. if self._packing_size[dtype_str] > self._param_pack_thd:
  216. self._pack(dtype_str)
  217. return self._futures_dict[param]
  218. def _flush(self):
  219. for dtype in sorted(self._packing_list.keys()):
  220. self._pack(dtype)
  221. for param in self._params:
  222. grad = self._gradients_dict[param]
  223. grad = copy(grad, self._grad_origin_device[param])
  224. self._futures_dict[param].set(grad)
  225. self._reset()
  226. make_allreduce_cb = AllreduceCallback