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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 megengine.device import get_default_device, get_device_count
  17. from ..core._imperative_rt.core2 import apply
  18. from ..core.ops.builtin import ParamPackConcat, ParamPackSplit
  19. from ..functional.tensor import copy
  20. from ..tensor import Tensor
  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"""
  27. Returns split tensor to tensor list as offsets and shapes described,
  28. only used for ``parampack``.
  29. :param inp: input tensor.
  30. :param 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. :param shapes: tensor shapes of outputs.
  34. :return: splitted tensors.
  35. Examples:
  36. .. testcode::
  37. import numpy as np
  38. from megengine import tensor
  39. from megengine.distributed.helper import param_pack_split
  40. a = tensor(np.ones((10,), np.int32))
  41. b, c = param_pack_split(a, [0, 1, 1, 10], [(1,), (3, 3)])
  42. print(b.numpy())
  43. print(c.numpy())
  44. Outputs:
  45. .. testoutput::
  46. [1]
  47. [[1 1 1]
  48. [1 1 1]
  49. [1 1 1]]
  50. """
  51. op = ParamPackSplit()
  52. op.offsets = offsets
  53. op.shapes = [s or (1,) for s in shapes]
  54. outputs = apply(op, inp)
  55. for s, x in zip(shapes, outputs):
  56. if not s:
  57. x._setscalar()
  58. return outputs
  59. def param_pack_concat(inps: list, offsets: Tensor, offsets_val: list):
  60. r"""
  61. Returns concated tensor, only used for ``parampack``.
  62. :param inps: input tensors.
  63. :param offsets: device value of offsets.
  64. :param offsets_val: offsets of inputs, length of `2 * n`,
  65. format `[begin0, end0, begin1, end1]`.
  66. :return: concated tensor.
  67. Examples:
  68. .. testcode::
  69. import numpy as np
  70. from megengine import tensor
  71. from megengine.distributed.helper import param_pack_concat
  72. a = tensor(np.ones((1,), np.int32))
  73. b = tensor(np.ones((3, 3), np.int32))
  74. offsets_val = [0, 1, 1, 10]
  75. offsets = tensor(offsets_val, np.int32)
  76. c = param_pack_concat([a, b], offsets, offsets_val)
  77. print(c.numpy())
  78. Outputs:
  79. .. testoutput::
  80. [1 1 1 1 1 1 1 1 1 1]
  81. """
  82. op = ParamPackConcat()
  83. op.offsets = offsets_val
  84. return apply(op, *inps, offsets)[0]
  85. def get_offsets(shapes):
  86. offsets = []
  87. offset = 0
  88. for shape in shapes:
  89. offsets.append(offset)
  90. offset += int(np.prod(shape))
  91. offsets.append(offset)
  92. return offsets
  93. _enable_p2p_cache = None
  94. def _check_enable_p2p():
  95. global _enable_p2p_cache
  96. if _enable_p2p_cache is not None:
  97. return _enable_p2p_cache
  98. cmd = ["nvidia-smi", "topo", "-p2p", "w"]
  99. import subprocess
  100. output = subprocess.run(cmd, stdout=subprocess.PIPE).stdout
  101. if output.count(b"OK") > 1:
  102. _enable_p2p_cache = True
  103. return True
  104. else:
  105. _enable_p2p_cache = False
  106. return False
  107. def pack_allreduce_split(pack_list, shapes, group, reduce_method):
  108. offsets_val = get_offsets(shapes)
  109. offsets = Tensor(offsets_val)
  110. packed_grads = param_pack_concat(pack_list, offsets, offsets_val)
  111. packed_grads = all_reduce_sum(packed_grads, group, group.comp_node)
  112. if reduce_method == "mean":
  113. packed_grads /= group.size
  114. grads = param_pack_split(packed_grads, offsets_val, shapes)
  115. return grads
  116. class TensorFuture(Future):
  117. def device(self):
  118. raise "Sorry, this tensor is not ready"
  119. def numpy(self):
  120. raise "Sorry, this tensor is not ready"
  121. def shape(self):
  122. raise "Sorry, this tensor is not ready"
  123. def dtype(self):
  124. raise "Sorry, this tensor is not ready"
  125. def synchronized(func: Callable):
  126. """
  127. Decorator. Decorated function will synchronize when finished.
  128. Specifically, we use this to prevent data race during hub.load"""
  129. @functools.wraps(func)
  130. def wrapper(*args, **kwargs):
  131. if not is_distributed():
  132. return func(*args, **kwargs)
  133. ret = func(*args, **kwargs)
  134. group_barrier()
  135. return ret
  136. return wrapper
  137. def _get_device_count_worker(queue, device_type):
  138. num = get_device_count(device_type)
  139. queue.put(num)
  140. def _check_device_initialized(device_type: str):
  141. try:
  142. test = Tensor(1, device=device_type)
  143. inited = False
  144. del test
  145. except:
  146. inited = True
  147. errmsg = "The cuda env is set before the forked thread starts. Please do not use any cuda function or variable before forking."
  148. if inited:
  149. raise RuntimeError(errmsg)
  150. def get_device_count_by_fork(device_type: str):
  151. """
  152. Get device count in fork thread.
  153. See https://stackoverflow.com/questions/22950047/cuda-initialization-error-after-fork
  154. for more information.
  155. """
  156. q = mp.Queue()
  157. p = mp.Process(target=_get_device_count_worker, args=(q, device_type))
  158. p.start()
  159. p.join()
  160. return q.get()
  161. def bcast_list_(inps: list, group: Group = WORLD):
  162. """
  163. Broadcast tensors between given group.
  164. :param inps: input tensors.
  165. :param group: communication group.
  166. """
  167. for inp in inps:
  168. inp._reset(_bcast_param(inp, group))
  169. class AllreduceCallback:
  170. """
  171. Allreduce Callback with tensor fusion optimization.
  172. :param reduce_method: the method to reduce gradiants.
  173. :param group: communication group.
  174. :param backend: override distributed backend in allreduce
  175. """
  176. def __init__(self, reduce_method: str, group: Group = WORLD, backend: str = None):
  177. reduce_method = reduce_method.lower()
  178. assert reduce_method in ["sum", "mean"], "reduce_method should be sum or mean"
  179. self._reduce_method = reduce_method
  180. self._group = group
  181. self._marked_gm = WeakSet()
  182. self._param_pack_thd = 10 * 1024 * 1024
  183. self._reset()
  184. if backend is None:
  185. assert _group._sd, "please call init_process_group first"
  186. backend = _group._sd.backend
  187. if backend == "auto":
  188. if group.is_single_machine and not _check_enable_p2p():
  189. backend = "shm"
  190. else:
  191. backend = "nccl"
  192. self._backend = backend
  193. def _reset(self):
  194. self._params = []
  195. self._gradients_dict = dict()
  196. self._futures_dict = dict()
  197. self._packing_list = defaultdict(list)
  198. self._packing_size = defaultdict(int)
  199. self._grad_origin_device = dict()
  200. def _pack(self, dtype):
  201. if len(self._packing_list[dtype]) == 0:
  202. return
  203. grad_list = [self._gradients_dict[p] for p in self._packing_list[dtype]]
  204. shapes = [p._tuple_shape for p in self._packing_list[dtype]]
  205. with override_backend(self._backend):
  206. reduced_grads = pack_allreduce_split(
  207. grad_list, shapes, self._group, self._reduce_method
  208. )
  209. for param, grad in zip(self._packing_list[dtype], reduced_grads):
  210. self._gradients_dict[param] = grad
  211. self._packing_list[dtype] = []
  212. self._packing_size[dtype] = 0
  213. def __call__(self, param, grad):
  214. gm = get_backwarding_grad_manager()
  215. assert isinstance(gm, GradManager)
  216. if gm not in self._marked_gm:
  217. gm._register_after_backward_callback(self._flush)
  218. self._marked_gm.add(gm)
  219. self._params.append(param)
  220. self._futures_dict[param] = TensorFuture(ack=False)
  221. self._gradients_dict[param] = grad
  222. self._grad_origin_device[param] = str(grad.device)
  223. dtype_str = str(np.dtype(param.dtype))
  224. dtype_size = np.dtype(param.dtype).itemsize
  225. self._packing_list[dtype_str].append(param)
  226. self._packing_size[dtype_str] += int(np.prod(param._tuple_shape)) * dtype_size
  227. if self._packing_size[dtype_str] > self._param_pack_thd:
  228. self._pack(dtype_str)
  229. return self._futures_dict[param]
  230. def _flush(self):
  231. for dtype in sorted(self._packing_list.keys()):
  232. self._pack(dtype)
  233. for param in self._params:
  234. grad = self._gradients_dict[param]
  235. grad = copy(grad, self._grad_origin_device[param])
  236. self._futures_dict[param].set(grad)
  237. self._reset()
  238. make_allreduce_cb = AllreduceCallback

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台