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

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