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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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 ..functional.param_pack import get_offsets, pack_allreduce_split
  18. from ..functional.utils import copy
  19. from ..utils.future import Future
  20. from .functional import all_reduce_sum, broadcast
  21. from .group import WORLD, Group, group_barrier, is_distributed
  22. class TensorFuture(Future):
  23. def device(self):
  24. raise "Sorry, this tensor is not ready"
  25. def numpy(self):
  26. raise "Sorry, this tensor is not ready"
  27. def shape(self):
  28. raise "Sorry, this tensor is not ready"
  29. def dtype(self):
  30. raise "Sorry, this tensor is not ready"
  31. def synchronized(func: Callable):
  32. """Decorator. Decorated function will synchronize when finished.
  33. Specifically, we use this to prevent data race during hub.load"""
  34. @functools.wraps(func)
  35. def wrapper(*args, **kwargs):
  36. if not is_distributed():
  37. return func(*args, **kwargs)
  38. ret = func(*args, **kwargs)
  39. group_barrier()
  40. return ret
  41. return wrapper
  42. def _get_device_count_worker(queue, device_type):
  43. num = get_device_count(device_type)
  44. queue.put(num)
  45. def get_device_count_by_fork(device_type: str):
  46. """Get device count in fork thread.
  47. See https://stackoverflow.com/questions/22950047/cuda-initialization-error-after-fork
  48. for more information.
  49. """
  50. q = mp.Queue()
  51. p = mp.Process(target=_get_device_count_worker, args=(q, device_type))
  52. p.start()
  53. p.join()
  54. return q.get()
  55. def bcast_list_(inps: list, group: Group = WORLD):
  56. """Broadcast tensors between given group.
  57. :param inps: input tensors.
  58. :param group: communication group.
  59. """
  60. for inp in inps:
  61. inp._reset(broadcast(inp, group))
  62. class AllreduceCallback:
  63. """Allreduce Callback with tensor fusion optimization.
  64. :param reduce_method: the method to reduce gradiants.
  65. :param group: communication group.
  66. """
  67. def __init__(self, reduce_method: str, group: Group = WORLD):
  68. reduce_method = reduce_method.lower()
  69. assert reduce_method in ["sum", "mean"], "reduce_method should be sum or mean"
  70. self._reduce_method = reduce_method
  71. self._group = group
  72. self._marked_gm = WeakSet()
  73. self._param_pack_thd = 10 * 1024 * 1024
  74. self._reset()
  75. def _reset(self):
  76. self._params = []
  77. self._gradients_dict = dict()
  78. self._futures_dict = dict()
  79. self._packing_list = defaultdict(list)
  80. self._packing_size = defaultdict(int)
  81. self._grad_origin_device = dict()
  82. def _pack(self, dtype):
  83. grad_list = [self._gradients_dict[p] for p in self._packing_list[dtype]]
  84. shapes = [p.shape for p in self._packing_list[dtype]]
  85. reduced_grads = pack_allreduce_split(
  86. grad_list, shapes, self._group, self._reduce_method
  87. )
  88. for param, grad in zip(self._packing_list[dtype], reduced_grads):
  89. self._gradients_dict[param] = grad
  90. self._packing_list[dtype] = []
  91. self._packing_size[dtype] = 0
  92. def __call__(self, param, grad):
  93. gm = get_backwarding_grad_manager()
  94. assert isinstance(gm, GradManager)
  95. if gm not in self._marked_gm:
  96. gm._register_after_backward_callback(self._flush)
  97. self._marked_gm.add(gm)
  98. self._params.append(param)
  99. self._futures_dict[param] = TensorFuture(ack=False)
  100. self._gradients_dict[param] = grad
  101. self._grad_origin_device[param] = str(grad.device)
  102. dtype_str = str(np.dtype(param.dtype))
  103. dtype_size = np.dtype(param.dtype).itemsize
  104. self._packing_list[dtype_str].append(param)
  105. self._packing_size[dtype_str] += int(np.prod(param.shape)) * dtype_size
  106. if self._packing_size[dtype_str] > self._param_pack_thd:
  107. self._pack(dtype_str)
  108. return self._futures_dict[param]
  109. def _flush(self):
  110. for dtype in sorted(self._packing_list.keys()):
  111. self._pack(dtype)
  112. for param in self._params:
  113. grad = self._gradients_dict[param]
  114. grad = copy(grad, self._grad_origin_device[param])
  115. self._futures_dict[param].set(grad)
  116. self._reset()
  117. make_allreduce_cb = AllreduceCallback

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