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

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