tracker.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # Copyright 2019 Kakao Brain
  2. #
  3. # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
  4. #
  5. # This source code is licensed under the BSD license found in the
  6. # LICENSE file in the root directory of this source tree.
  7. """Tracks skip tensors on a thread."""
  8. from contextlib import contextmanager
  9. import threading
  10. from typing import Dict, Generator, List, Optional, Tuple
  11. from torch import Tensor
  12. from ..checkpoint import is_checkpointing
  13. from ..dependency import fork, join
  14. from ..microbatch import Batch
  15. from ..stream import AbstractStream
  16. from .layout import SkipLayout
  17. from .namespace import Namespace
  18. from .portal import Portal
  19. __all__: List[str] = []
  20. class SkipTracker:
  21. """Tracks saved skip tensors.
  22. It will update the given micro-batch in place. This is because when it
  23. manipulates the underlying skip tensors, the current micro-batch also has
  24. to be connected with the skip tensors.
  25. One thread has one skip tracker. Call :func:`current_skip_tracker` to get
  26. the skip tracker on the current thread.
  27. """
  28. def __init__(self) -> None:
  29. self.tensors: Dict[Tuple[Namespace, str], Optional[Tensor]] = {}
  30. def save(self, batch: Batch, ns: Namespace, name: str, tensor: Optional[Tensor]) -> None:
  31. self.tensors[(ns, name)] = tensor
  32. def load(self, batch: Batch, ns: Namespace, name: str) -> Optional[Tensor]:
  33. return self.tensors.pop((ns, name))
  34. def copy(
  35. self, batch: Batch, prev_stream: AbstractStream, next_stream: AbstractStream, ns: Namespace, name: str,
  36. ) -> None:
  37. raise TypeError("copy is not supported for non-portal skip tensors")
  38. class SkipTrackerThroughPotals(SkipTracker):
  39. """Tracks saved skip tensors through portals. The skip tensors will be
  40. hidden in portals so that the autograd engine does not need to track them.
  41. This tracker is only used when the training or evaluating module is wrapped
  42. with :class:`torchpipe.Pipe`.
  43. """
  44. def __init__(self, skip_layout: SkipLayout) -> None:
  45. super().__init__()
  46. self.skip_layout = skip_layout
  47. self.portals: Dict[Tuple[Namespace, str], Portal] = {}
  48. def save(self, batch: Batch, ns: Namespace, name: str, tensor: Optional[Tensor]) -> None:
  49. """Saves the stashed skip tensor in a portal. The portal is then
  50. connected to the given micro-batch with :class:`Join`.
  51. """
  52. if not self.skip_layout.requires_copy(ns, name):
  53. super().save(batch, ns, name, tensor)
  54. return
  55. # See [Tensor Life of Portal] at Portal.put_tensor() to understand the
  56. # below tensor_life values. Here are the selected events which retrieve
  57. # the tensor in portal:
  58. #
  59. # 1. [x] blue()
  60. # ...
  61. # 6. [x] PortalOrange.forward
  62. # ...
  63. # 8. [x] PortalOrange.forward (recomputed)
  64. # ...
  65. # 11. [x] blue() (recomputed)
  66. #
  67. if (ns, name) not in self.portals:
  68. if is_checkpointing():
  69. # Under checkpointing, the tensor used by the first
  70. # PortalOrange should be alive in the portal. This tensor will
  71. # be used again by the second PortalOrange during the
  72. # recomputation.
  73. tensor_life = 3 # Delete at [8. PortalOrange.forward (recomputed)]
  74. else:
  75. tensor_life = 2 # Delete at [6. PortalOrange.forward]
  76. portal = Portal(tensor, tensor_life)
  77. self.portals[(ns, name)] = portal
  78. else:
  79. # Under recomputation, the portal already exists.
  80. portal = self.portals[(ns, name)]
  81. # The existing tensor life already became 0. It should be reset as
  82. # 1 to delete the tensor after the second PortalBlue immediately.
  83. tensor_life = 1 # Delete at [11. blue() (recomputed)]
  84. portal.put_tensor(tensor, tensor_life)
  85. phony = portal.blue()
  86. tensor_idx = batch.find_tensor_idx()
  87. batch[tensor_idx] = join(batch[tensor_idx], phony)
  88. def load(self, batch: Batch, ns: Namespace, name: str) -> Optional[Tensor]:
  89. """Loads a skip tensor from the corresponding portal to pop. The given
  90. micro-batch is connected to the portal with :class:`Fork`.
  91. """
  92. if not self.skip_layout.requires_copy(ns, name):
  93. tensor = super().load(batch, ns, name)
  94. return tensor
  95. portal = self.portals[(ns, name)]
  96. tensor_idx = batch.find_tensor_idx()
  97. batch[tensor_idx], phony = fork(batch[tensor_idx])
  98. tensor = portal.orange(phony)
  99. return tensor
  100. def copy(
  101. self, batch: Batch, prev_stream: AbstractStream, next_stream: AbstractStream, ns: Namespace, name: str,
  102. ) -> None:
  103. """Copies the skip tensor in the corresponding portal. The given
  104. micro-batch and the portal will be tied with :class:`Fork` and
  105. :class:`Join`.
  106. """
  107. assert self.skip_layout.requires_copy(ns, name)
  108. tensor_idx = batch.find_tensor_idx()
  109. batch[tensor_idx], phony = fork(batch[tensor_idx])
  110. portal = self.portals[(ns, name)]
  111. phony = portal.copy(prev_stream, next_stream, phony)
  112. batch[tensor_idx] = join(batch[tensor_idx], phony)
  113. class ThreadLocal(threading.local):
  114. def __init__(self) -> None:
  115. self.skip_tracker: Optional[SkipTracker] = None
  116. thread_local = ThreadLocal()
  117. @contextmanager
  118. def use_skip_tracker(skip_tracker: SkipTracker) -> Generator[None, None, None]:
  119. """Registers the given skip tracker on the current thread within a
  120. context::
  121. with use_skip_tracker(my_skip_tracker):
  122. ...
  123. """
  124. orig = thread_local.skip_tracker
  125. thread_local.skip_tracker = skip_tracker
  126. try:
  127. yield
  128. finally:
  129. thread_local.skip_tracker = orig
  130. def current_skip_tracker() -> SkipTracker:
  131. """Gets the skip tracker on the current thread."""
  132. skip_tracker = thread_local.skip_tracker
  133. if skip_tracker is None:
  134. skip_tracker = SkipTracker()
  135. thread_local.skip_tracker = skip_tracker
  136. return skip_tracker