dlpack.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. from typing import Any
  2. import torch
  3. import enum
  4. from torch._C import _from_dlpack
  5. from torch._C import _to_dlpack as to_dlpack
  6. class DLDeviceType(enum.IntEnum):
  7. # Enums as in DLPack specification (aten/src/ATen/dlpack.h)
  8. kDLCPU = 1,
  9. kDLGPU = 2,
  10. kDLCPUPinned = 3,
  11. kDLOpenCL = 4,
  12. kDLVulkan = 7,
  13. kDLMetal = 8,
  14. kDLVPI = 9,
  15. kDLROCM = 10,
  16. kDLExtDev = 12,
  17. torch._C._add_docstr(to_dlpack, r"""to_dlpack(tensor) -> PyCapsule
  18. Returns an opaque object (a "DLPack capsule") representing the tensor.
  19. .. note::
  20. ``to_dlpack`` is a legacy DLPack interface. The capsule it returns
  21. cannot be used for anything in Python other than use it as input to
  22. ``from_dlpack``. The more idiomatic use of DLPack is to call
  23. ``from_dlpack`` directly on the tensor object - this works when that
  24. object has a ``__dlpack__`` method, which PyTorch and most other
  25. libraries indeed have now.
  26. .. warning::
  27. Only call ``from_dlpack`` once per capsule produced with ``to_dlpack``.
  28. Behavior when a capsule is consumed multiple times is undefined.
  29. Args:
  30. tensor: a tensor to be exported
  31. The DLPack capsule shares the tensor's memory.
  32. """)
  33. # TODO: add a typing.Protocol to be able to tell Mypy that only objects with
  34. # __dlpack__ and __dlpack_device__ methods are accepted.
  35. def from_dlpack(ext_tensor: Any) -> 'torch.Tensor':
  36. """from_dlpack(ext_tensor) -> Tensor
  37. Converts a tensor from an external library into a ``torch.Tensor``.
  38. The returned PyTorch tensor will share the memory with the input tensor
  39. (which may have come from another library). Note that in-place operations
  40. will therefore also affect the data of the input tensor. This may lead to
  41. unexpected issues (e.g., other libraries may have read-only flags or
  42. immutable data structures), so the user should only do this if they know
  43. for sure that this is fine.
  44. Args:
  45. ext_tensor (object with ``__dlpack__`` attribute, or a DLPack capsule):
  46. The tensor or DLPack capsule to convert.
  47. If ``ext_tensor`` is a tensor (or ndarray) object, it must support
  48. the ``__dlpack__`` protocol (i.e., have a ``ext_tensor.__dlpack__``
  49. method). Otherwise ``ext_tensor`` may be a DLPack capsule, which is
  50. an opaque ``PyCapsule`` instance, typically produced by a
  51. ``to_dlpack`` function or method.
  52. Examples::
  53. >>> import torch.utils.dlpack
  54. >>> t = torch.arange(4)
  55. # Convert a tensor directly (supported in PyTorch >= 1.10)
  56. >>> t2 = torch.from_dlpack(t)
  57. >>> t2[:2] = -1 # show that memory is shared
  58. >>> t2
  59. tensor([-1, -1, 2, 3])
  60. >>> t
  61. tensor([-1, -1, 2, 3])
  62. # The old-style DLPack usage, with an intermediate capsule object
  63. >>> capsule = torch.utils.dlpack.to_dlpack(t)
  64. >>> capsule
  65. <capsule object "dltensor" at ...>
  66. >>> t3 = torch.from_dlpack(capsule)
  67. >>> t3
  68. tensor([-1, -1, 2, 3])
  69. >>> t3[0] = -9 # now we're sharing memory between 3 tensors
  70. >>> t3
  71. tensor([-9, -1, 2, 3])
  72. >>> t2
  73. tensor([-9, -1, 2, 3])
  74. >>> t
  75. tensor([-9, -1, 2, 3])
  76. """
  77. if hasattr(ext_tensor, '__dlpack__'):
  78. device = ext_tensor.__dlpack_device__()
  79. # device is either CUDA or ROCm, we need to pass the current
  80. # stream
  81. if device[0] in (DLDeviceType.kDLGPU, DLDeviceType.kDLROCM):
  82. stream = torch.cuda.current_stream('cuda:{}'.format(device[1]))
  83. # cuda_stream is the pointer to the stream and it is a public
  84. # attribute, but it is not documented
  85. # The array API specify that the default legacy stream must be passed
  86. # with a value of 1 for CUDA
  87. # https://data-apis.org/array-api/latest/API_specification/array_object.html?dlpack-self-stream-none#dlpack-self-stream-none # NOQA
  88. is_cuda = device[0] == DLDeviceType.kDLGPU
  89. # Since pytorch is not using PTDS by default, lets directly pass
  90. # the legacy stream
  91. stream_ptr = 1 if is_cuda and stream.cuda_stream == 0 else stream.cuda_stream
  92. dlpack = ext_tensor.__dlpack__(stream=stream_ptr)
  93. else:
  94. dlpack = ext_tensor.__dlpack__()
  95. else:
  96. # Old versions just call the converter
  97. dlpack = ext_tensor
  98. return _from_dlpack(dlpack)