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.

grad_manager.py 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import weakref
  2. from collections import defaultdict
  3. from contextlib import contextmanager
  4. from typing import Callable
  5. from ..core.autodiff.grad import Grad
  6. from ..logger import get_logger
  7. from ..tensor import Tensor
  8. from ..utils.future import Future
  9. logger = get_logger(__name__)
  10. backwarding_grad_manager = None
  11. def get_backwarding_grad_manager():
  12. return backwarding_grad_manager
  13. class AttachSpec:
  14. __slots__ = "tensor", "callbacks"
  15. class GradManager:
  16. r"""
  17. GradManager computes gradients or more generally, vector-Jacobian product, by reverse mode
  18. automatic differentiation (a.k.a. back propagation).
  19. Reverse mode autodiff normally reuses many intermediate tensors for best computation efficiency.
  20. In a read-eval-print-loop (REPL) environment however, it is impossible to known how the user
  21. would take gradients later thus which tensors to keep. To solve this problem, the user must
  22. somehow declare beforehand which gradient could possibly be taken. With GradManager, users are
  23. required to call the :meth:`attach` method on a tensor if they want to take gradients with
  24. respect to it later. Furthermore, any computation on a tensor before it is attached is
  25. completely ignored from the autodiff perspective, so :meth:`attach` must be called before any
  26. computation that needs differentiation.
  27. For example, the following symbolic differentiation code
  28. .. code-block::
  29. x = get_x()
  30. y = f(x)
  31. dy = ones_like(y)
  32. dx = vjp(y, x, dy) # vector-Jacobian product
  33. can be rewriten using GradManager for REPL environment as
  34. .. code-block::
  35. with GradManager() as gm:
  36. x = get_x()
  37. gm.attach(x) # must be placed before any computation on x that needs differentiation
  38. y = f(x)
  39. dy = ones_like(y)
  40. gm.backward(y, dy) # doesn't need x, already known via attach()
  41. dx = x.grad # backward() saves result to .grad attribute
  42. A more realistic example of training a neural network would be like
  43. .. code-block::
  44. gm = GradManager()
  45. gm.attach(model.parameters())
  46. for data in dataset:
  47. with gm:
  48. loss = model(data)
  49. gm.backward(loss)
  50. # gradients w.r.t. parameters is accumulated into their .grad attributes
  51. You can also use ``record()`` and ``release()`` method instead of ``with`` context:
  52. .. code-block::
  53. gm = GradManager()
  54. gm.attach(model.parameters())
  55. for data in dataset:
  56. gm.record()
  57. loss = model(data)
  58. gm.backward(loss)
  59. # backward() will clear recorded history and free resources
  60. # call release() if backward() is not called
  61. # gm.release()
  62. For your convenience, GradManager may (not must) be reused. As shown in the examples, you
  63. only need to attach a tensor once and GradManager will remember it afterwards.
  64. However, a single GradManager can record only one computation history at a time. To run
  65. multiple differentiations simultaneously or perform high order differentiation, create
  66. as many GradManager as you need.
  67. .. note::
  68. Mutable tensors introduce ambiguities when doing symbolic differentiation: which version
  69. of the tensor are we referring to? For attached tensors, GradManager resolves this
  70. ambiguity by "snapshoting" them on first encounter, either on :meth:`record` (or entering
  71. with statement) if tensor is attached before :meth:`record`, or on :meth:`attach` if
  72. GradManager is already recording. Attached tensors will then be interpreted as their
  73. snapshotted version for differentiation purpose. The same ambiguity on the first parameter
  74. of :meth:`backward` is simply resolved by using the latest version.
  75. Typically, in data parallel, we would like to average the gradients across
  76. processes. Users will finally get the averaged gradients if an "AllReduce"
  77. callback is registered as follows:
  78. .. code-block::
  79. import megengine.distributed as dist
  80. gm = GradManager()
  81. gm.attach(model.parameters(), callback=dist.make_allreduce_cb("MEAN"))
  82. """
  83. def __init__(self):
  84. self._attach_specs = {} # id(Tensor) -> AttachSpec
  85. self._recording = False
  86. self._grad = None
  87. self._after_backward_callback = []
  88. self._gradients = {}
  89. def attach(self, tensors: list, callbacks=None):
  90. r"""
  91. Instruct GradManager to track operations on tensors, so that gradients with respect
  92. to those tensors could be evaluated later.
  93. :meth:`attach` also accepts a list of callbacks, which will be called with the tensor and
  94. its gradient during :meth:`backward`. The signature of callbacks should look like:
  95. .. code-block::
  96. def callback(tensor: Tensor, grad: Tensor) -> Tensor:
  97. ...
  98. # returned grad is passed to subsequent callbacks
  99. # and finally accumulated to the .grad attribute of tensor
  100. return grad
  101. :meth:`attach` calls with overlapping tensors will result in their callbacks concatenated,
  102. independently for each tensor. For example,
  103. .. code-block::
  104. gm.attach([x, y], callbacks=[f])
  105. gm.attach([y], callbacks=[g])
  106. is equivalent to
  107. .. code-block::
  108. gm.attach([x], callbacks=[f])
  109. gm.attach([y], callbacks=[f, g])
  110. The effect of :meth:`attach` will persist across multiple uses of the GradManager. When
  111. reusing a GradManager, it is likely a mistake to call :meth:`attach` on the same set of
  112. tensors and callbacks repeatedly, which may grow the callback list indefinitely.
  113. .. note::
  114. When reusing a GradManager, it is sometimes desirable to attach temporary tensors each
  115. time, e.g. for computing gradients of inputs of a neural network. GradManager tries to
  116. accommodate such usages by holding weak references to attached tensors. Most of the
  117. times, this should be enough to prevent resource leak. Unfortunately, there are still
  118. some pitfalls left:
  119. - Callbacks should not hold strong references, directly or indirectly, to attached
  120. tensors. Any strong reference, including those from callbacks, will prevent
  121. garbage collection (even by the cycle collector!) of a attached tensor, until
  122. the GradManager object is garbage collected.
  123. Please also note that GradManager might hold additional strong references to attached
  124. tensors when it is in use. This note only covers potential resource leaks across
  125. multiple uses of a GradManager, which is unrelated to whether resources is timely
  126. released within a single use.
  127. :param tensors: tensor or list of tensors to track
  128. :param callbacks: callback or list of callbacks
  129. """
  130. if callbacks is None:
  131. callbacks = []
  132. if isinstance(callbacks, Callable):
  133. callbacks = [callbacks]
  134. if isinstance(tensors, Tensor):
  135. tensors = [tensors]
  136. def make_spec(tensor):
  137. selfref = weakref.ref(self)
  138. key = id(tensor)
  139. def deleter(_):
  140. self = selfref()
  141. if self is not None:
  142. del self._attach_specs[key]
  143. spec = AttachSpec()
  144. spec.tensor = weakref.ref(tensor, deleter)
  145. spec.callbacks = []
  146. return spec
  147. for x in tensors:
  148. spec = self._attach_specs.get(id(x))
  149. new_attach = spec is None
  150. if spec is None:
  151. spec = make_spec(x)
  152. self._attach_specs[id(x)] = spec
  153. spec.callbacks.extend(callbacks)
  154. if new_attach and self._recording:
  155. self._do_record(spec)
  156. return self
  157. def _register_after_backward_callback(self, callback):
  158. self._after_backward_callback.append(callback)
  159. return self
  160. def backward(self, y=None, dy=None):
  161. r"""
  162. Compute gradients (or vector-Jacobian product) for all attached tensors, accumulate to
  163. corresponding .grad attribute, and release resources along the way.
  164. :meth:`backward` computes the vector-Jacobian product :math:`dx_j = \sum_{i} dy_i J_{ij}`
  165. where :math:`J_{ij} = ∂y_i/∂x_j` is the Jacobian matrix between vector variables :math:`y`
  166. and :math:`x`, with all vectors involved represented as a list of tensors, in the sense of
  167. direct sums (or flatten-and-concatenate). :math:`y` and :math:`dy` are passed as the first
  168. and second parameter respectively, whereas :math:`x` is directly taken from the list of
  169. all attached tensors. The result :math:`dx` is also not returned. Instead, it is directly
  170. accumulated into the .grad attribute of matching attached tensors (a.k.a. :math:`x`). This
  171. can be done unambiguously since :math:`dx` as a list of tensors has the same structure as
  172. :math:`x`.
  173. If :math:`y` is a scalar and :math:`dy` is chosen to be 1, the vector-Jacobian product
  174. yield gradient of :math:`y` with repect to :math:`x` as a special case. In that case,
  175. you will be able to omit the :math:`dy` parameter and :meth:`backward` will automatically
  176. use 1 for it and compute the gradient.
  177. :meth:`backward` consumes all resources held by this GradManager and releases them in the
  178. process of this call. When the call successfully finishes, the GradManager will be put back
  179. to an inactive state.
  180. :param y: tensor or list of tensors
  181. :param dy: tensor or list of tensors. Defaults to 1 if y is scalar
  182. """
  183. from ..functional import ones_like
  184. global backwarding_grad_manager
  185. cache = backwarding_grad_manager
  186. backwarding_grad_manager = self
  187. if not self._recording:
  188. raise RuntimeError(
  189. "no computation history. "
  190. "did you forget record() or "
  191. "call a method that clears the history?"
  192. )
  193. assert self._grad is not None
  194. if y is None:
  195. ys = []
  196. elif isinstance(y, (tuple, list)):
  197. ys = y
  198. else:
  199. ys = [y]
  200. if dy is None:
  201. dys = [ones_like(y) for y in ys]
  202. elif isinstance(dy, (tuple, list)):
  203. dys = ys
  204. else:
  205. dys = [dy]
  206. try:
  207. self._grad(ys, dys)
  208. for callback in self._after_backward_callback:
  209. callback()
  210. for id_, grad in self._gradients.items():
  211. if isinstance(grad, Future):
  212. grad = grad.get()
  213. spec = self._attach_specs.get(id_)
  214. tensor = spec and spec.tensor()
  215. if tensor is not None:
  216. if tensor.grad is None:
  217. tensor.grad = grad
  218. else:
  219. tensor.grad += grad
  220. finally:
  221. self.release()
  222. backwarding_grad_manager = cache
  223. def record(self):
  224. r"""
  225. Start recording operations
  226. After this call, you will be able to call :meth:`backward`.
  227. """
  228. if self._recording:
  229. raise RuntimeError("already recording")
  230. grad = Grad()
  231. self._recording = True
  232. self._grad = grad
  233. for spec in self._attach_specs.values():
  234. self._do_record(spec)
  235. grad.__enter__()
  236. def _do_record(self, spec):
  237. tensor = spec.tensor()
  238. if tensor is None:
  239. return
  240. def callback(_, grad, callbacks=spec.callbacks):
  241. for cb in callbacks:
  242. grad = cb(tensor, grad)
  243. self._gradients[id(tensor)] = grad
  244. # NOTE: override prev callback wrt when called serval times
  245. self._grad.wrt(tensor, callback=callback)
  246. def release(self):
  247. r"""
  248. Stop recording operations and release resources kept for gradient computation
  249. After this call, you will not be able to call :meth:`backward`.
  250. """
  251. if self._grad is not None:
  252. self._grad.__exit__(None, None, None)
  253. self._grad = None
  254. self._recording = False
  255. self._gradients = dict()
  256. def __enter__(self):
  257. self.record()
  258. return self
  259. def __exit__(self, exc_type, exc_val, exc_tb):
  260. self.release()

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