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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 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.ops.builtin import ParamPackConcat, ParamPackSplit
  18. from ..core.tensor.core import apply
  19. from ..functional.utils import copy
  20. from ..tensor import Tensor
  21. from ..utils.future import Future
  22. from .functional import all_reduce_sum, broadcast
  23. from .group import WORLD, Group, group_barrier, is_distributed
  24. def param_pack_split(inp: Tensor, offsets: list, shapes: list):
  25. r"""
  26. Returns split tensor to tensor list as offsets and shapes described,
  27. only used for ``parampack``.
  28. :param inp: input tensor.
  29. :param offsets: offsets of outputs, length of `2 * n`,
  30. while n is tensor nums you want to split,
  31. format `[begin0, end0, begin1, end1]`.
  32. :param shapes: tensor shapes of outputs.
  33. :return: splitted tensors.
  34. Examples:
  35. .. testcode::
  36. import numpy as np
  37. from megengine import tensor
  38. from megengine.distributed.helper import param_pack_split
  39. a = tensor(np.ones((10,), np.int32))
  40. b, c = param_pack_split(a, [0, 1, 1, 10], [(1,), (3, 3)])
  41. print(b.numpy())
  42. print(c.numpy())
  43. Outputs:
  44. .. testoutput::
  45. [1]
  46. [[1 1 1]
  47. [1 1 1]
  48. [1 1 1]]
  49. """
  50. op = ParamPackSplit()
  51. op.offsets = offsets
  52. op.shapes = shapes
  53. return apply(op, inp)
  54. def param_pack_concat(inps: list, offsets: Tensor, offsets_val: list):
  55. r"""
  56. Returns concated tensor, only used for ``parampack``.
  57. :param inps: input tensors.
  58. :param offsets: device value of offsets.
  59. :param offsets_val: offsets of inputs, length of `2 * n`,
  60. format `[begin0, end0, begin1, end1]`.
  61. :return: concated tensor.
  62. Examples:
  63. .. testcode::
  64. import numpy as np
  65. from megengine import tensor
  66. from megengine.distributed.helper import param_pack_concat
  67. a = tensor(np.ones((1,), np.int32))
  68. b = tensor(np.ones((3, 3), np.int32))
  69. offsets_val = [0, 1, 1, 10]
  70. offsets = tensor(offsets_val, np.int32)
  71. c = param_pack_concat([a, b], offsets, offsets_val)
  72. print(c.numpy())
  73. Outputs:
  74. .. testoutput::
  75. [1 1 1 1 1 1 1 1 1 1]
  76. """
  77. op = ParamPackConcat()
  78. op.offsets = offsets_val
  79. return apply(op, *inps, offsets)[0]
  80. def get_offsets(shapes):
  81. offsets = []
  82. offset = 0
  83. for shape in shapes:
  84. offsets.append(offset)
  85. offset += int(np.prod(shape))
  86. offsets.append(offset)
  87. return offsets
  88. def pack_allreduce_split(pack_list, shapes, group, reduce_method):
  89. offsets_val = get_offsets(shapes)
  90. offsets = Tensor(offsets_val)
  91. packed_grads = param_pack_concat(pack_list, offsets, offsets_val)
  92. packed_grads = all_reduce_sum(packed_grads, group, group.comp_node)
  93. if reduce_method == "mean":
  94. packed_grads /= group.size
  95. grads = param_pack_split(packed_grads, offsets_val, shapes)
  96. return grads
  97. class TensorFuture(Future):
  98. def device(self):
  99. raise "Sorry, this tensor is not ready"
  100. def numpy(self):
  101. raise "Sorry, this tensor is not ready"
  102. def shape(self):
  103. raise "Sorry, this tensor is not ready"
  104. def dtype(self):
  105. raise "Sorry, this tensor is not ready"
  106. def synchronized(func: Callable):
  107. """Decorator. Decorated function will synchronize when finished.
  108. Specifically, we use this to prevent data race during hub.load"""
  109. @functools.wraps(func)
  110. def wrapper(*args, **kwargs):
  111. if not is_distributed():
  112. return func(*args, **kwargs)
  113. ret = func(*args, **kwargs)
  114. group_barrier()
  115. return ret
  116. return wrapper
  117. def _get_device_count_worker(queue, device_type):
  118. num = get_device_count(device_type)
  119. queue.put(num)
  120. def get_device_count_by_fork(device_type: str):
  121. """Get device count in fork thread.
  122. See https://stackoverflow.com/questions/22950047/cuda-initialization-error-after-fork
  123. for more information.
  124. """
  125. q = mp.Queue()
  126. p = mp.Process(target=_get_device_count_worker, args=(q, device_type))
  127. p.start()
  128. p.join()
  129. return q.get()
  130. def bcast_list_(inps: list, group: Group = WORLD):
  131. """Broadcast tensors between given group.
  132. :param inps: input tensors.
  133. :param group: communication group.
  134. """
  135. for inp in inps:
  136. inp._reset(broadcast(inp, group))
  137. class AllreduceCallback:
  138. """Allreduce Callback with tensor fusion optimization.
  139. :param reduce_method: the method to reduce gradiants.
  140. :param group: communication group.
  141. """
  142. def __init__(self, reduce_method: str, group: Group = WORLD):
  143. reduce_method = reduce_method.lower()
  144. assert reduce_method in ["sum", "mean"], "reduce_method should be sum or mean"
  145. self._reduce_method = reduce_method
  146. self._group = group
  147. self._marked_gm = WeakSet()
  148. self._param_pack_thd = 10 * 1024 * 1024
  149. self._reset()
  150. def _reset(self):
  151. self._params = []
  152. self._gradients_dict = dict()
  153. self._futures_dict = dict()
  154. self._packing_list = defaultdict(list)
  155. self._packing_size = defaultdict(int)
  156. self._grad_origin_device = dict()
  157. def _pack(self, dtype):
  158. grad_list = [self._gradients_dict[p] for p in self._packing_list[dtype]]
  159. shapes = [p.shape for p in self._packing_list[dtype]]
  160. reduced_grads = pack_allreduce_split(
  161. grad_list, shapes, self._group, self._reduce_method
  162. )
  163. for param, grad in zip(self._packing_list[dtype], reduced_grads):
  164. self._gradients_dict[param] = grad
  165. self._packing_list[dtype] = []
  166. self._packing_size[dtype] = 0
  167. def __call__(self, param, grad):
  168. gm = get_backwarding_grad_manager()
  169. assert isinstance(gm, GradManager)
  170. if gm not in self._marked_gm:
  171. gm._register_after_backward_callback(self._flush)
  172. self._marked_gm.add(gm)
  173. self._params.append(param)
  174. self._futures_dict[param] = TensorFuture(ack=False)
  175. self._gradients_dict[param] = grad
  176. self._grad_origin_device[param] = str(grad.device)
  177. dtype_str = str(np.dtype(param.dtype))
  178. dtype_size = np.dtype(param.dtype).itemsize
  179. self._packing_list[dtype_str].append(param)
  180. self._packing_size[dtype_str] += int(np.prod(param.shape)) * dtype_size
  181. if self._packing_size[dtype_str] > self._param_pack_thd:
  182. self._pack(dtype_str)
  183. return self._futures_dict[param]
  184. def _flush(self):
  185. for dtype in sorted(self._packing_list.keys()):
  186. self._pack(dtype)
  187. for param in self._params:
  188. grad = self._gradients_dict[param]
  189. grad = copy(grad, self._grad_origin_device[param])
  190. self._futures_dict[param].set(grad)
  191. self._reset()
  192. make_allreduce_cb = AllreduceCallback

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