copy.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. """Autograd functions for stream-aware CUDA copy. It is used to overlap copy
  8. and computation on the same GPU.
  9. """
  10. from collections import deque
  11. from typing import Deque, List, Optional, Tuple, Sequence
  12. import torch
  13. from torch import Tensor
  14. from .stream import AbstractStream, current_stream, get_device, record_stream, use_stream, wait_stream
  15. __all__: List[str] = ["Context", "Copy", "Wait"]
  16. Tensors = Sequence[Tensor]
  17. # Common interface between :class:`Copy` and :class:`Wait`.
  18. class Context:
  19. prev_stream: AbstractStream
  20. next_stream: AbstractStream
  21. class Copy(torch.autograd.Function):
  22. """Copies tensors on specific streams."""
  23. @staticmethod
  24. # type: ignore[override]
  25. def forward(ctx: Context, prev_stream: AbstractStream, next_stream: AbstractStream, *input,) -> Tensors:
  26. ctx.prev_stream = prev_stream
  27. ctx.next_stream = next_stream
  28. output = []
  29. output_stream = current_stream(get_device(next_stream))
  30. with use_stream(prev_stream), use_stream(next_stream):
  31. for x in input:
  32. if torch.is_tensor(x):
  33. y = x.to(get_device(next_stream), non_blocking=True)
  34. output.append(y)
  35. # 'prev_stream' is not where 'x' has been allocated.
  36. record_stream(x, prev_stream)
  37. # 'y' has been allocated on 'next_stream'.
  38. # It might be used on the current stream captured as 'output_stream'.
  39. record_stream(y, output_stream)
  40. else:
  41. output.append(x)
  42. return tuple(output)
  43. @staticmethod
  44. def backward(ctx: Context, *grad_output: Tensor,) -> Tuple[Optional[Tensor], ...]:
  45. prev_stream = ctx.prev_stream
  46. next_stream = ctx.next_stream
  47. grad_input: Deque[Tensor] = deque(maxlen=len(grad_output))
  48. input_stream = current_stream(get_device(prev_stream))
  49. with use_stream(prev_stream), use_stream(next_stream):
  50. for x in reversed(grad_output):
  51. y = x.to(get_device(prev_stream), non_blocking=True)
  52. grad_input.appendleft(y)
  53. # 'next_stream' is not where 'x' has been allocated.
  54. record_stream(x, next_stream)
  55. # 'y' has been allocated on 'prev_stream'.
  56. # It might be used on the current stream captured as 'input_stream'.
  57. record_stream(y, input_stream)
  58. grad_streams: Tuple[Optional[Tensor], ...] = (None, None)
  59. return grad_streams + tuple(grad_input)
  60. class Wait(torch.autograd.Function):
  61. """Synchronizes a stream to another stream.
  62. Place it just before you want to start an operation on the next stream,
  63. provided that all operations on the previous stream are done.
  64. """
  65. @staticmethod
  66. # type: ignore[override]
  67. def forward(ctx: Context, prev_stream: AbstractStream, next_stream: AbstractStream, *input) -> Tensors:
  68. ctx.prev_stream = prev_stream
  69. ctx.next_stream = next_stream
  70. wait_stream(next_stream, prev_stream)
  71. return tuple(x.detach() if torch.is_tensor(x) else x for x in input)
  72. @staticmethod
  73. def backward(ctx: Context, *grad_input: Tensor,) -> Tuple[Optional[Tensor], ...]:
  74. prev_stream = ctx.prev_stream
  75. next_stream = ctx.next_stream
  76. wait_stream(prev_stream, next_stream)
  77. grad_streams: Tuple[Optional[Tensor], ...] = (None, None)
  78. return grad_streams + grad_input