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

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

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