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

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