graph.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. import abc
  2. import contextlib
  3. import functools
  4. import logging
  5. import threading
  6. from collections import defaultdict, deque
  7. from collections.abc import (
  8. Callable,
  9. Generator,
  10. Iterable,
  11. Iterator,
  12. MutableMapping,
  13. Sequence,
  14. )
  15. from typing import (
  16. Any,
  17. cast,
  18. Literal,
  19. NamedTuple,
  20. Optional,
  21. TYPE_CHECKING,
  22. TypeAlias,
  23. Union,
  24. )
  25. from weakref import WeakKeyDictionary, WeakValueDictionary
  26. import torch
  27. from torch.autograd.variable import Variable
  28. from torch.utils._python_dispatch import TorchDispatchMode
  29. from torch.utils.hooks import RemovableHandle
  30. if TYPE_CHECKING:
  31. from torch._ops import OpOverload
  32. __all__ = [
  33. "saved_tensors_hooks",
  34. "save_on_cpu",
  35. "disable_saved_tensors_hooks",
  36. "register_multi_grad_hook",
  37. "allow_mutation_on_saved_tensors",
  38. "Node",
  39. "GradientEdge",
  40. "get_gradient_edge",
  41. "increment_version",
  42. "set_warn_on_accumulate_grad_stream_mismatch",
  43. ]
  44. log = logging.getLogger(__name__)
  45. class Node(abc.ABC):
  46. @abc.abstractmethod
  47. def name(self) -> str:
  48. r"""Return the name.
  49. Example::
  50. >>> import torch
  51. >>> a = torch.tensor([0., 0., 0.], requires_grad=True)
  52. >>> b = a.clone()
  53. >>> assert isinstance(b.grad_fn, torch.autograd.graph.Node)
  54. >>> print(b.grad_fn.name())
  55. CloneBackward0
  56. """
  57. raise NotImplementedError
  58. @property
  59. @abc.abstractmethod
  60. def next_functions(self) -> tuple[tuple[Optional["Node"], int], ...]:
  61. raise NotImplementedError
  62. @abc.abstractmethod
  63. def metadata(self) -> dict:
  64. r"""Return the metadata."""
  65. raise NotImplementedError
  66. @property
  67. @abc.abstractmethod
  68. def _input_metadata(self) -> list[Any]:
  69. raise NotImplementedError
  70. @abc.abstractmethod
  71. def _register_hook_dict(self, tensor: torch.Tensor) -> None:
  72. raise NotImplementedError
  73. @abc.abstractmethod
  74. def register_hook(self, fn: Callable[..., Any]) -> RemovableHandle:
  75. r"""Register a backward hook.
  76. The hook will be called every time a gradient with respect to the
  77. Node is computed. The hook should have the following signature::
  78. hook(grad_inputs: Tuple[Tensor], grad_outputs: Tuple[Tensor]) -> Tuple[Tensor] or None
  79. The hook should not modify its argument, but it can optionally return
  80. a new gradient which will be used in place of :attr:`grad_inputs`.
  81. This function returns a handle with a method ``handle.remove()``
  82. that removes the hook from the module.
  83. .. note::
  84. See :ref:`backward-hooks-execution` for more information on how when this hook
  85. is executed, and how its execution is ordered relative to other hooks.
  86. .. note::
  87. In the rare case where the hook is registered while the Node has already
  88. begun execution, there is no longer any guarantee on :attr:`grad_outputs`
  89. content (it might be as usual or empty depending on other factors). The
  90. hook can still optionally return a new gradient to be used in place of
  91. :attr:`grad_inputs` independent of :attr:`grad_outputs`.
  92. Example::
  93. >>> import torch
  94. >>> a = torch.tensor([0., 0., 0.], requires_grad=True)
  95. >>> b = a.clone()
  96. >>> assert isinstance(b.grad_fn, torch.autograd.graph.Node)
  97. >>> handle = b.grad_fn.register_hook(lambda gI, gO: (gO[0] * 2,))
  98. >>> b.sum().backward(retain_graph=True)
  99. >>> print(a.grad)
  100. tensor([2., 2., 2.])
  101. >>> handle.remove() # Removes the hook
  102. >>> a.grad = None
  103. >>> b.sum().backward(retain_graph=True)
  104. >>> print(a.grad)
  105. tensor([1., 1., 1.])
  106. """
  107. raise NotImplementedError
  108. @abc.abstractmethod
  109. def register_prehook(self, fn: Callable[..., Any]) -> RemovableHandle:
  110. r"""Register a backward pre-hook.
  111. The hook will be called every time a gradient with respect to the
  112. Node is computed. The hook should have the following signature::
  113. hook(grad_outputs: Tuple[Tensor]) -> Tuple[Tensor] or None
  114. The hook should not modify its argument, but it can optionally return
  115. a new gradient which will be used in place of :attr:`grad_outputs`.
  116. This function returns a handle with a method ``handle.remove()``
  117. that removes the hook from the module.
  118. .. note::
  119. See :ref:`backward-hooks-execution` for more information on how when this hook
  120. is executed, and how its execution is ordered relative to other hooks.
  121. Example::
  122. >>> a = torch.tensor([0., 0., 0.], requires_grad=True)
  123. >>> b = a.clone()
  124. >>> assert isinstance(b.grad_fn, torch.autograd.graph.Node)
  125. >>> handle = b.grad_fn.register_prehook(lambda gI: (gI[0] * 2,))
  126. >>> b.sum().backward(retain_graph=True)
  127. >>> print(a.grad)
  128. tensor([2., 2., 2.])
  129. >>> handle.remove()
  130. >>> a.grad = None
  131. >>> b.sum().backward(retain_graph=True)
  132. >>> print(a.grad)
  133. tensor([1., 1., 1.])
  134. """
  135. raise NotImplementedError
  136. @classmethod
  137. def __subclasshook__(cls, subclass: type) -> bool:
  138. if cls is Node and (
  139. (
  140. subclass is not None
  141. and subclass is getattr(torch._C._functions, subclass.__name__, None)
  142. )
  143. or issubclass(subclass, torch.autograd.function.BackwardCFunction)
  144. ):
  145. return True
  146. return NotImplemented
  147. def _get_grad_fn_or_grad_acc(t: Union[torch.Tensor, "GradientEdge"]) -> Node:
  148. if isinstance(t, GradientEdge):
  149. return t.node
  150. if t.requires_grad and t.grad_fn is None:
  151. with torch.enable_grad():
  152. node = t.view_as(t).grad_fn.next_functions[0][0] # type: ignore[union-attr]
  153. else:
  154. node = t.grad_fn
  155. if node is None:
  156. raise AssertionError("Expected gradient function to be set")
  157. return node
  158. class GradientEdge(NamedTuple):
  159. """Object representing a given gradient edge within the autograd graph.
  160. To get the gradient edge where a given Tensor gradient will be computed,
  161. you can do ``edge = autograd.graph.get_gradient_edge(tensor)``.
  162. """
  163. node: Node
  164. output_nr: int
  165. # This token can be used to ensure the graph stays alive when it cannot be
  166. # done via the node field
  167. ownership_token: Optional[Node] = None
  168. def get_gradient_edge(tensor: torch.Tensor) -> GradientEdge:
  169. """Get the gradient edge for computing the gradient of the given Tensor.
  170. In particular, it is equivalent to call
  171. ``g = autograd.grad(loss, input)`` and ``g = autograd.grad(loss, get_gradient_edge(input))``.
  172. """
  173. if not tensor.requires_grad:
  174. raise RuntimeError(
  175. "It is not possible to get the gradient edge for a Tensor "
  176. "that does not require gradients",
  177. )
  178. grad_fn = _get_grad_fn_or_grad_acc(tensor)
  179. # Python-based Node are owned by the C++ side meaning the python grad_fn
  180. # object we hold here does NOT keep the C++ graph alive.
  181. # Create an ownership token by creating a new C++ node that own the graph
  182. # we care about here.
  183. token = None
  184. if isinstance(grad_fn, torch._C._FunctionBase):
  185. with torch.enable_grad():
  186. token = tensor.view_as(tensor).grad_fn
  187. # Note that output_nr default to 0 which is the right value
  188. # for the AccumulateGrad node.
  189. # pyrefly: ignore [bad-argument-type]
  190. return GradientEdge(grad_fn, tensor.output_nr, ownership_token=token)
  191. def increment_version(tensor: Union[torch.Tensor, Iterable[torch.Tensor]]) -> None:
  192. """Update autograd metadata tracking whether the given Tensor was modified in place.
  193. This is to enable more accurate error checking within the autograd engine.
  194. It is already done automatically by PyTorch functions and within custom Function
  195. when mark_dirty() is called appropriately so you only need to call this explicitly
  196. if you are doing inplace operation on the Tensor data in a way that Pytorch doesn't
  197. know about. For example a custom kernel that reads the Tensor data_ptr and modifies
  198. the memory inplace based on this pointer. Can accept either a tensor, or a list of tensors.
  199. Note that incrementing the version counter multiple times for a single inplace operation
  200. is not problematic.
  201. Note that if you pass in tensor constructed under torch.inference_mode(),
  202. we will not bump its version counter (because your tensor does not have one).
  203. """
  204. if isinstance(tensor, torch.Tensor):
  205. tensor = (tensor,)
  206. torch._C._increment_version(tensor)
  207. class saved_tensors_hooks:
  208. """Context-manager that sets a pair of pack / unpack hooks for saved tensors.
  209. Use this context-manager to define how intermediary results of an operation
  210. should be packed before saving, and unpacked on retrieval.
  211. In that context, the ``pack_hook`` function will be called every time an
  212. operation saves a tensor for backward (this includes intermediary results
  213. saved using
  214. :func:`~torch.autograd.function._ContextMethodMixin.save_for_backward` but
  215. also those recorded by a PyTorch-defined operation). The output of
  216. ``pack_hook`` is then stored in the computation graph instead of the
  217. original tensor.
  218. The ``unpack_hook`` is called when the saved tensor needs to be accessed,
  219. namely when executing :func:`torch.Tensor.backward()` or
  220. :func:`torch.autograd.grad()`. It takes as argument the *packed* object
  221. returned by ``pack_hook`` and should return a tensor which has the same
  222. content as the original tensor (passed as input to the corresponding
  223. ``pack_hook``).
  224. The hooks should have the following signatures:
  225. pack_hook(tensor: Tensor) -> Any
  226. unpack_hook(Any) -> Tensor
  227. where the return value of ``pack_hook`` is a valid input to ``unpack_hook``.
  228. In general, you want ``unpack_hook(pack_hook(t))`` to be equal to ``t`` in terms
  229. of value, size, dtype and device.
  230. Example::
  231. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
  232. >>> def pack_hook(x):
  233. ... print("Packing", x)
  234. ... return x.detach()
  235. >>>
  236. >>> def unpack_hook(x):
  237. ... print("Unpacking", x)
  238. ... return x
  239. >>>
  240. >>> a = torch.ones(5, requires_grad=True)
  241. >>> b = torch.ones(5, requires_grad=True) * 2
  242. >>> with torch.autograd.graph.saved_tensors_hooks(pack_hook, unpack_hook):
  243. ... y = a * b
  244. Packing tensor([1., 1., 1., 1., 1.], requires_grad=True)
  245. Packing tensor([2., 2., 2., 2., 2.], grad_fn=<MulBackward0>)
  246. >>> y.sum().backward()
  247. Unpacking tensor([1., 1., 1., 1., 1.], requires_grad=True)
  248. Unpacking tensor([2., 2., 2., 2., 2.], grad_fn=<MulBackward0>)
  249. .. warning ::
  250. Performing an inplace operation on the input to either hooks may lead
  251. to undefined behavior.
  252. .. warning ::
  253. Only one pair of hooks is allowed at a time. When recursively nesting this
  254. context-manager, only the inner-most pair of hooks will be applied.
  255. .. warning ::
  256. To avoid reference cycle, the return value of ``pack_hook`` cannot hold a
  257. reference to the input tensor. For example, use `lambda x: x.detach()`
  258. instead of `lambda x: x` as the pack hook.
  259. """
  260. def __init__(
  261. self,
  262. pack_hook: Callable[[torch.Tensor], Any],
  263. unpack_hook: Callable[[Any], torch.Tensor],
  264. ) -> None:
  265. self.pack_hook = pack_hook
  266. self.unpack_hook = unpack_hook
  267. def __enter__(self) -> None:
  268. torch._C._autograd._push_saved_tensors_default_hooks(
  269. self.pack_hook, self.unpack_hook
  270. )
  271. def __exit__(self, *args: object) -> None:
  272. torch._C._autograd._pop_saved_tensors_default_hooks()
  273. class save_on_cpu(saved_tensors_hooks):
  274. """Context manager under which tensors saved by the forward pass will be stored on cpu, then retrieved for backward.
  275. When performing operations within this context manager, intermediary
  276. results saved in the graph during the forward pass will be moved to CPU,
  277. then copied back to the original device when needed for the backward pass.
  278. If the graph was already on CPU, no tensor copy is performed.
  279. Use this context-manager to trade compute for GPU memory usage (e.g.
  280. when your model doesn't fit in GPU memory during training).
  281. Args:
  282. pin_memory (bool): If ``True`` tensors will be saved to CPU pinned memory
  283. during packing and copied to GPU asynchronously during unpacking.
  284. Defaults to ``False``.
  285. Also see :ref:`cuda-memory-pinning`.
  286. Example::
  287. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  288. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
  289. >>> a = torch.randn(5, requires_grad=True, device="cuda")
  290. >>> b = torch.randn(5, requires_grad=True, device="cuda")
  291. >>> c = torch.randn(5, requires_grad=True, device="cuda")
  292. >>>
  293. >>> def f(a, b, c):
  294. ... prod_1 = a * b # a and b are saved on GPU
  295. ... with torch.autograd.graph.save_on_cpu():
  296. ... prod_2 = prod_1 * c # prod_1 and c are saved on CPU
  297. ... y = prod_2 * a # prod_2 and a are saved on GPU
  298. ... return y
  299. >>>
  300. >>> y = f(a, b, c)
  301. >>> del a, b, c # for illustration only
  302. >>> # the content of a, b, and prod_2 are still alive on GPU
  303. >>> # the content of prod_1 and c only live on CPU
  304. >>> y.sum().backward() # all CPU tensors are moved back to GPU, for backward
  305. >>> # all intermediary tensors are released (deleted) after the call to backward
  306. """
  307. def __init__(self, pin_memory: bool = False, device_type: str = "cuda") -> None:
  308. device_module = getattr(torch, device_type, torch.cuda)
  309. def pack_to_cpu(tensor: torch.Tensor) -> tuple[torch.device, torch.Tensor]:
  310. if not pin_memory:
  311. return (tensor.device, tensor.cpu())
  312. packed = torch.empty(
  313. tensor.size(),
  314. dtype=tensor.dtype,
  315. layout=tensor.layout,
  316. pin_memory=(device_module.is_available() and not tensor.is_sparse),
  317. )
  318. packed.copy_(tensor)
  319. return (tensor.device, packed)
  320. def unpack_from_cpu(packed: tuple[torch.device, torch.Tensor]) -> torch.Tensor:
  321. device, tensor = packed
  322. return tensor.to(device, non_blocking=pin_memory)
  323. super().__init__(pack_to_cpu, unpack_from_cpu)
  324. @contextlib.contextmanager
  325. def disable_saved_tensors_hooks(error_message: str) -> Generator[None, None, None]:
  326. """Context-manager that disables the saved tensors default hooks feature.
  327. Useful for if you are creating a feature that does not work with saved
  328. tensors default hooks.
  329. Args:
  330. error_message (str): When saved tensors default hooks are used when they
  331. have been are disabled, a RuntimeError with this
  332. error message gets raised.
  333. Example::
  334. >>> # xdoctest: +SKIP(failing)
  335. >>> message = "saved tensors default hooks are disabled"
  336. >>> with torch.autograd.graph.disable_saved_tensors_hooks(message):
  337. ... # Raises RuntimeError: saved tensors default hooks are disabled
  338. ... with torch.autograd.graph.save_on_cpu():
  339. ... pass
  340. """
  341. maybe_prev_message = None
  342. try:
  343. maybe_prev_message = (
  344. torch._C._autograd._saved_tensors_hooks_get_disabled_error_message()
  345. )
  346. torch._C._autograd._saved_tensors_hooks_disable(error_message)
  347. yield
  348. finally:
  349. # See NOTE: [disabled_error_message invariant]
  350. if maybe_prev_message is None:
  351. torch._C._autograd._saved_tensors_hooks_enable()
  352. else:
  353. torch._C._autograd._saved_tensors_hooks_disable(maybe_prev_message)
  354. def set_warn_on_accumulate_grad_stream_mismatch(enabled: bool) -> None:
  355. """Whether to warn when the AccumulateGrad node's stream does not match the stream
  356. of the node that produced the incoming gradient.
  357. """
  358. return torch._C._set_warn_on_accumulate_grad_stream_mismatch(enabled)
  359. class _MultiHandle(RemovableHandle):
  360. handles: tuple[RemovableHandle, ...]
  361. def __init__(self, handles: tuple[RemovableHandle, ...]) -> None:
  362. self.handles = handles
  363. def remove(self) -> None:
  364. for handle in self.handles:
  365. handle.remove()
  366. def __getstate__(self) -> tuple[RemovableHandle, ...]:
  367. return self.handles
  368. def __setstate__(self, state: tuple[RemovableHandle, ...]) -> None:
  369. self.handles = state
  370. def register_multi_grad_hook(
  371. tensors: Sequence[torch.Tensor],
  372. fn: Union[
  373. Callable[[Sequence[Optional[torch.Tensor]]], None],
  374. Callable[[torch.Tensor], None],
  375. ],
  376. *,
  377. mode: Literal["all", "any"] = "all",
  378. ) -> RemovableHandle:
  379. r"""Register a multi-grad backward hook.
  380. There are two supported modes: ``"all"`` and ``"any"``.
  381. Under the ``"all"`` mode, the hook will be called after gradients with respect to every tensor in
  382. :attr:`tensors` have been computed. If a tensor is in :attr:`tensors` but
  383. is not part of the graph, or if a tensor is not needed to compute the gradients
  384. for any ``inputs`` specified for the current ``.backward()`` or ``.grad()`` call,
  385. this tensor will be ignored and the hook will not wait for its gradient to be
  386. computed.
  387. After every non-ignored tensor's gradient has been computed, :attr:`fn` will be
  388. called with those gradients. ``None`` will be passed for tensors that did not
  389. have their gradients computed.
  390. Under the ``"any"`` mode, the hook will be called after the first gradient
  391. with respect to a tensor in :attr:`tensors` has been computed. The hook
  392. will be called with that gradient as its argument.
  393. The hook should not modify its arguments.
  394. This function returns a handle with a method ``handle.remove()`` that removes the hook.
  395. .. note::
  396. See :ref:`backward-hooks-execution` for more information on how when this hook
  397. is executed, and how its execution is ordered relative to other hooks.
  398. Example::
  399. >>> import torch
  400. >>>
  401. >>> a = torch.rand(2, 3, requires_grad=True)
  402. >>> b = torch.rand(2, 3, requires_grad=True)
  403. >>> c = a * b
  404. >>> d = a * b
  405. >>>
  406. >>> def fn(grads):
  407. ... print([g is not None for g in grads])
  408. ...
  409. >>> torch.autograd.graph.register_multi_grad_hook((a, b, c, d), fn)
  410. >>>
  411. >>> c.sum().backward(retain_graph=True)
  412. [True, True, True, False]
  413. >>> c.sum().backward(inputs=(a,), retain_graph=True)
  414. [True, False, True, False]
  415. >>>
  416. """
  417. supported_modes = ("all", "any")
  418. lock = threading.Lock()
  419. if mode not in supported_modes:
  420. raise ValueError(f"Expects mode to be one of {supported_modes} but got {mode}")
  421. if mode == "all":
  422. count: dict[int, int] = {}
  423. nb_calls = None
  424. buffer: dict[int, list[Optional[torch.Tensor]]] = {}
  425. grad_fns = list(map(_get_grad_fn_or_grad_acc, tensors))
  426. len_tensors = len(tensors)
  427. def get_inner_hook(idx: int) -> Callable[[torch.Tensor], None]:
  428. def inner_hook(grad: torch.Tensor) -> None:
  429. nonlocal count, nb_calls, buffer, fn
  430. id = torch._C._current_graph_task_id()
  431. if id == -1:
  432. raise AssertionError(
  433. "expected this hook to be called inside a backward call"
  434. )
  435. count[id] = count.get(id, 0)
  436. # pyrefly: ignore [unsupported-operation]
  437. buffer[id] = buffer.get(id, [None] * len_tensors)
  438. with lock:
  439. curr_count, count[id] = count[id], count[id] + 1
  440. if curr_count == 0:
  441. # On the first call, compute the actual nb_calls and buffer
  442. nb_calls = sum(
  443. map(torch._C._will_engine_execute_node, grad_fns)
  444. )
  445. buffer[id][idx] = grad
  446. if nb_calls is None:
  447. raise AssertionError("Expected nb_calls to be set")
  448. if curr_count == nb_calls - 1:
  449. fn = cast(Callable[[Sequence[Optional[torch.Tensor]]], None], fn)
  450. fn(buffer[id])
  451. del count[id]
  452. del buffer[id]
  453. return inner_hook
  454. handles = tuple(
  455. t.register_hook(get_inner_hook(i)) for i, t in enumerate(tensors)
  456. )
  457. elif mode == "any":
  458. fn = cast(Callable[[torch.Tensor], None], fn)
  459. ran_hook: dict[int, bool] = defaultdict(bool)
  460. @functools.wraps(fn)
  461. def wrapped_fn(grad: torch.Tensor) -> None:
  462. nonlocal ran_hook
  463. id = torch._C._current_graph_task_id()
  464. if id == -1:
  465. raise AssertionError(
  466. "expected this hook to be called inside a backward call"
  467. )
  468. with lock:
  469. prev, ran_hook[id] = ran_hook[id], True
  470. if prev:
  471. return
  472. fn(grad)
  473. handles = tuple(
  474. tensor.register_hook(wrapped_fn)
  475. for tensor in tensors
  476. if tensor.requires_grad
  477. )
  478. return _MultiHandle(handles) # type: ignore[possibly-undefined]
  479. # NOTE [Allow mutation on tensors saved for backward]
  480. #
  481. # 1. Tensor gets saved for backward
  482. # - remember the python object id and the version of the tensor
  483. # - remember aliasing information (data_ptr of base + version)
  484. # - save the original so we control its lifetime
  485. # 2. Any time a tensor gets in-placed
  486. # - for each tensor aliased to it:
  487. # - check using its object id and version to see if it has been saved
  488. # - if it has been saved, clone it
  489. # - delete the reference to the original
  490. # 3. during backward
  491. # - if the clone exists, the tensor must've been modified in-place
  492. _allow_mutation_on_saved_tensors_enabled: bool = False
  493. _TID: TypeAlias = tuple[int, int, int]
  494. _SID: TypeAlias = tuple[int, int]
  495. def _get_tid(tensor: torch.Tensor) -> _TID:
  496. # FIXME: This is almost definitely a bug.
  497. if isinstance(
  498. tensor,
  499. (
  500. torch._subclasses.fake_tensor.FakeTensor,
  501. torch._subclasses.functional_tensor.FunctionalTensor,
  502. ),
  503. ):
  504. data_ptr = 0
  505. else:
  506. data_ptr = tensor.data_ptr()
  507. return (id(tensor), data_ptr, tensor._version)
  508. def _get_sid(tensor: torch.Tensor) -> _SID:
  509. # FIXME: This is almost definitely a bug.
  510. if isinstance(
  511. tensor,
  512. (
  513. torch._subclasses.fake_tensor.FakeTensor,
  514. torch._subclasses.functional_tensor.FunctionalTensor,
  515. ),
  516. ):
  517. data_ptr = 0
  518. else:
  519. data_ptr = tensor.data_ptr()
  520. return (data_ptr, tensor._version)
  521. class _Handle:
  522. pass
  523. class _swap_with_cloned(saved_tensors_hooks):
  524. def __init__(self, ctx: "_AllowMutationOnSavedContext") -> None:
  525. def pack_hook(tensor: torch.Tensor) -> _Handle:
  526. tid = _get_tid(tensor)
  527. sid = _get_sid(tensor)
  528. # Tensors saved for backward have an entry in _tid_to_weakhandle
  529. handle: Optional[_Handle] = None
  530. # Save aliasing information
  531. ctx.sid_to_tid[sid].add(tid)
  532. # NB: The same tensor (of the same version) can be saved multiple times
  533. if tid not in ctx.tid_to_weakhandle:
  534. handle = _Handle()
  535. ctx.tid_to_weakhandle[tid] = handle
  536. ctx.original[handle] = tensor
  537. else:
  538. # Store an additional strong reference to the handle
  539. handle = ctx.tid_to_weakhandle[tid]
  540. return handle
  541. def unpack_hook(handle: _Handle) -> torch.Tensor:
  542. error_msg = (
  543. "Trying to backward outside of the 'allow_mutation_on_saved_tensors' context"
  544. "in which the graph was originally recorded."
  545. )
  546. if not _allow_mutation_on_saved_tensors_enabled:
  547. raise AssertionError(error_msg)
  548. if handle in ctx.cloned:
  549. res = ctx.cloned[handle]
  550. else:
  551. if handle not in ctx.original:
  552. raise AssertionError(error_msg)
  553. res = ctx.original[handle]
  554. return res
  555. super().__init__(pack_hook, unpack_hook)
  556. class _CloneArgBeforeMutateMode(TorchDispatchMode):
  557. def __init__(self, ctx: "_AllowMutationOnSavedContext") -> None:
  558. self.ctx = ctx
  559. def __torch_dispatch__(
  560. self,
  561. func: "OpOverload",
  562. types: Iterable[type],
  563. args: tuple[Any, ...] = (),
  564. kwargs: Optional[dict[Any, Any]] = None,
  565. ) -> Any:
  566. kwargs = kwargs or {}
  567. def maybe_clone(t: torch.Tensor) -> None:
  568. tid = _get_tid(t)
  569. sid = _get_sid(t)
  570. ctx = self.ctx
  571. if sid in ctx.sid_to_tid:
  572. for tid in ctx.sid_to_tid[sid]:
  573. if tid not in ctx.tid_to_weakhandle:
  574. # We know that if tid is in sid_to_tid, then it must also be in
  575. # tid_to_weakhandle. However, it is possible for the tensor to be
  576. # saved at one point, but cleared by backward before it is modified
  577. # in-place. Consider the following example:
  578. #
  579. # >>> a = torch.randn(2, 3, requires_grad=True).clone()
  580. # >>> out = (a**2).sum()
  581. # >>> out.backward()
  582. # >>> a.sin_()
  583. continue
  584. handle = ctx.tid_to_weakhandle[tid]
  585. if handle in ctx.cloned:
  586. # The same exact tensor has been cloned already
  587. continue
  588. ctx.cloned[handle] = ctx.original[handle].clone()
  589. del ctx.original[handle]
  590. for idx, arg in enumerate(func._schema.arguments):
  591. if arg.alias_info is not None and arg.alias_info.is_write:
  592. if arg.is_out:
  593. maybe_clone(kwargs["out"])
  594. elif isinstance(args[idx], list):
  595. # Foreach case. (Possible optimization: if most of the
  596. # tensors need to be cloned, use a for each clone?)
  597. for t in args[idx]:
  598. maybe_clone(t)
  599. else:
  600. maybe_clone(args[idx])
  601. return func(*args, **kwargs)
  602. class _AllowMutationOnSavedContext:
  603. def __init__(self) -> None:
  604. self.cloned: MutableMapping[_Handle, torch.Tensor] = WeakKeyDictionary()
  605. self.original: MutableMapping[_Handle, torch.Tensor] = WeakKeyDictionary()
  606. self.tid_to_weakhandle: MutableMapping[_TID, _Handle] = WeakValueDictionary()
  607. self.sid_to_tid: dict[_SID, set[_TID]] = defaultdict(set)
  608. def clear(self) -> None:
  609. self.cloned.clear()
  610. self.original.clear()
  611. self.tid_to_weakhandle.clear()
  612. self.sid_to_tid.clear()
  613. @contextlib.contextmanager
  614. def allow_mutation_on_saved_tensors() -> Generator[
  615. _AllowMutationOnSavedContext, None, None
  616. ]:
  617. """Context manager under which mutating tensors saved for backward is allowed.
  618. Under this context manager, tensors saved for backward are cloned on mutation,
  619. so the original version can still be used during backward. Normally, mutating a tensor
  620. saved for backward will result in an error raised when it's used during backward.
  621. To ensure the correct behavior, both the forward and backward should be run under
  622. the same context manager.
  623. Returns:
  624. An _AllowMutationOnSavedContext object storing the state managed by this
  625. context manager. This object can be useful for debugging purposes. The state
  626. managed by the context manager is automatically cleared upon exiting.
  627. Example::
  628. >>> import torch
  629. >>> with torch.autograd.graph.allow_mutation_on_saved_tensors():
  630. ... # forward
  631. ... a = torch.ones(2, 3, requires_grad=True)
  632. ... b = a.clone()
  633. ... out = (b**2).sum()
  634. ... b.sin_()
  635. ... # backward
  636. ... out.sum().backward()
  637. ...
  638. tensor([[0.8415, 0.8415, 0.8415],
  639. [0.8415, 0.8415, 0.8415]], grad_fn=<SinBackward0>)
  640. """
  641. global _allow_mutation_on_saved_tensors_enabled
  642. ctx = _AllowMutationOnSavedContext()
  643. with _swap_with_cloned(ctx), _CloneArgBeforeMutateMode(ctx):
  644. try:
  645. if _allow_mutation_on_saved_tensors_enabled:
  646. raise RuntimeError(
  647. "allow_mutation_on_saved_tensors contexts cannot be nested"
  648. )
  649. _allow_mutation_on_saved_tensors_enabled = True
  650. yield ctx
  651. finally:
  652. ctx.clear()
  653. _allow_mutation_on_saved_tensors_enabled = False
  654. def _register_logging_hooks_on_whole_graph(
  655. t_outputs: Sequence[Union[torch.Tensor, GradientEdge]],
  656. ) -> Callable[[], None]:
  657. grad_fns = list(map(_get_grad_fn_or_grad_acc, t_outputs))
  658. def iter_graph(roots: list[Node]) -> Iterator[Node]:
  659. if not roots:
  660. return
  661. seen: set[Node] = set()
  662. q: deque[Node] = deque()
  663. for node in roots:
  664. if node is not None:
  665. seen.add(node)
  666. q.append(node)
  667. while q:
  668. node = q.popleft()
  669. for fn, _ in node.next_functions:
  670. if fn in seen or fn is None:
  671. continue
  672. seen.add(fn)
  673. q.append(fn)
  674. yield node
  675. def fmt(t: Optional[torch.Tensor]) -> str:
  676. # Avoid circular import
  677. from torch.utils._dtype_abbrs import dtype_abbrs
  678. if t is None:
  679. return "None"
  680. return f"{dtype_abbrs[t.dtype]}[{', '.join(map(str, t.shape))}]"
  681. def prehook(grad_outputs: Sequence[Optional[torch.Tensor]]) -> None:
  682. node = torch._C._current_autograd_node()
  683. grad_outputs_str = f"[{','.join(fmt(t) for t in grad_outputs)}]"
  684. log_str = f"Executing: {node} with grad_outputs: {grad_outputs_str}"
  685. log.debug(log_str)
  686. handles = [node.register_prehook(prehook) for node in iter_graph(grad_fns)]
  687. def unregister_hooks() -> None:
  688. for handle in handles:
  689. handle.remove()
  690. return unregister_hooks
  691. def _engine_run_backward(
  692. t_outputs: Sequence[Union[torch.Tensor, GradientEdge]],
  693. *args: Any,
  694. **kwargs: Any,
  695. ) -> tuple[torch.Tensor, ...]:
  696. attach_logging_hooks = log.getEffectiveLevel() <= logging.DEBUG
  697. if attach_logging_hooks:
  698. unregister_hooks = _register_logging_hooks_on_whole_graph(t_outputs)
  699. try:
  700. return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
  701. t_outputs, *args, **kwargs
  702. ) # Calls into the C++ engine to run the backward pass
  703. finally:
  704. if attach_logging_hooks:
  705. unregister_hooks() # type: ignore[possibly-undefined]