forward_ad.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # mypy: allow-untyped-defs
  2. import os
  3. from typing import Any, NamedTuple, Optional
  4. import torch
  5. from .grad_mode import _DecoratorContextManager
  6. __all__ = [
  7. "UnpackedDualTensor",
  8. "enter_dual_level",
  9. "exit_dual_level",
  10. "make_dual",
  11. "unpack_dual",
  12. "dual_level",
  13. ]
  14. # Global variable used to make the python API simpler to use
  15. _current_level = -1
  16. def enter_dual_level():
  17. r"""Enter a new forward grad level.
  18. This level can be used to make and unpack dual Tensors to compute
  19. forward gradients.
  20. This function also updates the current level that is used by default
  21. by the other functions in this API.
  22. """
  23. global _current_level
  24. new_level = torch._C._enter_dual_level()
  25. if new_level != _current_level + 1:
  26. raise RuntimeError(
  27. "Entering a new forward AD level but the current level "
  28. "is not valid. Make sure you did not modified it directly."
  29. )
  30. _current_level = new_level
  31. return new_level
  32. def exit_dual_level(*, level=None):
  33. r"""Exit a forward grad level.
  34. This function deletes all the gradients associated with this
  35. level. Only deleting the latest entered level is allowed.
  36. This function also updates the current level that is used by default
  37. by the other functions in this API.
  38. """
  39. global _current_level
  40. if level is None:
  41. level = _current_level
  42. if level != _current_level:
  43. raise RuntimeError(
  44. "Trying to exit a forward AD level that was not the last one "
  45. "that was created. This is not supported."
  46. )
  47. torch._C._exit_dual_level(level=level)
  48. _current_level = level - 1
  49. def _maybe_load_decompositions():
  50. if os.environ.get("PYTORCH_JIT", "1") == "1" and __debug__:
  51. from torch._decomp import decompositions_for_jvp # noqa: F401
  52. def make_dual(tensor, tangent, *, level=None):
  53. r"""Associate a tensor value with its tangent to create a "dual tensor" for forward AD gradient computation.
  54. The result is a new tensor aliased to :attr:`tensor` with :attr:`tangent` embedded
  55. as an attribute as-is if it has the same storage layout or copied otherwise.
  56. The tangent attribute can be recovered with :func:`unpack_dual`.
  57. This function is backward differentiable.
  58. Given a function `f` whose jacobian is `J`, it allows one to compute the Jacobian-vector product (`jvp`)
  59. between `J` and a given vector `v` as follows.
  60. Example::
  61. >>> # xdoctest: +SKIP("Undefined variables")
  62. >>> with dual_level():
  63. ... inp = make_dual(x, v)
  64. ... out = f(inp)
  65. ... y, jvp = unpack_dual(out)
  66. Please see the `forward-mode AD tutorial <https://pytorch.org/tutorials/intermediate/forward_ad_usage.html>`__
  67. for detailed steps on how to use this API.
  68. """
  69. # See NOTE: [forward-mode AD decompositions mechanism]
  70. #
  71. # Import from torch._decomp import decompositions_for_jvp to register
  72. # decompositions for jvp to the jit registry
  73. #
  74. # FIXME: We specify that __debug__ must be True because
  75. # if python is run with -OO or -O flags (i.e., __debug__ is False), we encounter the
  76. # following error:
  77. #
  78. # Return value was annotated as having type Tuple[NoneType, NoneType] but is actually of
  79. # type Tuple[Tensor, Tensor]:
  80. # File ".../torch/_decomp/__init__.py", line 1585
  81. # else:
  82. # buffer = z
  83. # return min - torch.log1p(z), buffer
  84. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <--- HERE
  85. _maybe_load_decompositions()
  86. if level is None:
  87. level = _current_level
  88. if level < 0:
  89. raise RuntimeError(
  90. "Trying to create a dual Tensor for forward AD but no level "
  91. "exists, make sure to enter_dual_level() first."
  92. )
  93. if not (tensor.is_floating_point() or tensor.is_complex()):
  94. raise ValueError(
  95. f"Expected primal to be floating point or complex, but got: {tensor.dtype}"
  96. )
  97. if not (tangent.is_floating_point() or tangent.is_complex()):
  98. raise ValueError(
  99. f"Expected tangent to be floating point or complex, but got: {tangent.dtype}"
  100. )
  101. return torch._VF._make_dual(tensor, tangent, level=level)
  102. class UnpackedDualTensor(NamedTuple):
  103. r"""Namedtuple returned by :func:`unpack_dual` containing the primal and tangent components of the dual tensor.
  104. See :func:`unpack_dual` for more details.
  105. """
  106. primal: torch.Tensor
  107. tangent: Optional[torch.Tensor]
  108. def unpack_dual(tensor, *, level=None):
  109. r"""Unpack a "dual tensor" to get both its Tensor value and its forward AD gradient.
  110. The result is a namedtuple ``(primal, tangent)`` where ``primal`` is a view of
  111. :attr:`tensor`'s primal and ``tangent`` is :attr:`tensor`'s tangent as-is.
  112. Neither of these tensors can be dual tensor of level :attr:`level`.
  113. This function is backward differentiable.
  114. Example::
  115. >>> # xdoctest: +SKIP("Undefined variables")
  116. >>> with dual_level():
  117. ... inp = make_dual(x, x_t)
  118. ... out = f(inp)
  119. ... y, jvp = unpack_dual(out)
  120. ... jvp = unpack_dual(out).tangent
  121. Please see the `forward-mode AD tutorial <https://pytorch.org/tutorials/intermediate/forward_ad_usage.html>`__
  122. for detailed steps on how to use this API.
  123. """
  124. if level is None:
  125. level = _current_level
  126. if level < 0:
  127. return UnpackedDualTensor(tensor, None)
  128. primal, dual = torch._VF._unpack_dual(tensor, level=level)
  129. return UnpackedDualTensor(primal, dual)
  130. class dual_level(_DecoratorContextManager):
  131. r"""Context-manager for forward AD, where all forward AD computation must occur within the ``dual_level`` context.
  132. .. Note::
  133. The ``dual_level`` context appropriately enters and exit the dual level to
  134. controls the current forward AD level, which is used by default by the other
  135. functions in this API.
  136. We currently don't plan to support nested ``dual_level`` contexts, however, so
  137. only a single forward AD level is supported. To compute higher-order
  138. forward grads, one can use :func:`torch.func.jvp`.
  139. Example::
  140. >>> # xdoctest: +SKIP("Undefined variables")
  141. >>> x = torch.tensor([1])
  142. >>> x_t = torch.tensor([1])
  143. >>> with dual_level():
  144. ... inp = make_dual(x, x_t)
  145. ... # Do computations with inp
  146. ... out = your_fn(inp)
  147. ... _, grad = unpack_dual(out)
  148. >>> grad is None
  149. False
  150. >>> # After exiting the level, the grad is deleted
  151. >>> _, grad_after = unpack_dual(out)
  152. >>> grad is None
  153. True
  154. Please see the `forward-mode AD tutorial <https://pytorch.org/tutorials/intermediate/forward_ad_usage.html>`__
  155. for detailed steps on how to use this API.
  156. """
  157. def __enter__(self):
  158. return enter_dual_level()
  159. def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
  160. exit_dual_level()
  161. # Private helper functions
  162. _is_fwd_grad_enabled = torch._C._is_fwd_grad_enabled
  163. # Private helper function to enable or disable fwd grad.
  164. # If you're a user and want to use this, please file an issue to discuss the use case.
  165. class _set_fwd_grad_enabled(_DecoratorContextManager):
  166. def __init__(self, mode: bool) -> None:
  167. self.prev = _is_fwd_grad_enabled()
  168. torch._C._set_fwd_grad_enabled(mode)
  169. def __enter__(self) -> None:
  170. pass
  171. def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
  172. torch._C._set_fwd_grad_enabled(self.prev)