PyTorch C DLPack Extension
An internal PyTorch C Extension that facilitates interoperability between PyTorch tensors and C/C++ libraries via DLPack. It is not intended for direct external use by end-users, primarily serving as a utility within the PyTorch ecosystem. Version 0.1.5 is the current release, and its release cadence is tied to PyTorch's internal development.
Warnings
- gotcha This library is primarily an internal utility of PyTorch and is not intended for direct use by external users. Its API may change without warning, and it may not follow standard semantic versioning conventions for external consumption.
- gotcha Functionality heavily relies on PyTorch being installed. Ensure `torch` is available in your environment, as it's a peer dependency not explicitly listed in `install_requires`.
- gotcha The `to_dlpack` and `from_dlpack` functions are designed to operate on `torch.Tensor` objects. Passing objects of other types will result in runtime errors, often from the underlying C extension.
Install
-
pip install torch-c-dlpack-ext
Imports
- to_dlpack, from_dlpack
from torch_c_dlpack_ext import to_dlpack, from_dlpack
Quickstart
import torch
# WARNING: This library is primarily an internal utility of PyTorch
# and is not intended for direct use by external users. The API may change
# without warning and may not follow semantic versioning for external consumption.
try:
from torch_c_dlpack_ext import to_dlpack, from_dlpack
except ImportError:
print("ERROR: torch-c-dlpack-ext not installed or failed to import.")
print("This library is an internal utility and not meant for direct use.")
print("Please ensure 'torch' is also installed.")
exit(1)
print("Successfully imported torch_c_dlpack_ext (internal utility).")
# 1. Create a PyTorch tensor
tensor_orig = torch.randn(2, 3)
print(f"\nOriginal PyTorch Tensor:\n{tensor_orig}")
# 2. Convert to DLPack capsule
dlpack_capsule = to_dlpack(tensor_orig)
print(f"\nDLPack Capsule (type): {type(dlpack_capsule)}")
# 3. Convert back to a PyTorch tensor
tensor_restored = from_dlpack(dlpack_capsule)
print(f"\nRestored PyTorch Tensor (from DLPack):\n{tensor_restored}")
# 4. Verify data (DLPack shares underlying memory, so data should be identical)
print(f"\nAre restored and original tensor data close? {torch.allclose(tensor_orig, tensor_restored)}")
print(f"Are restored and original tensors the exact same Python object? {tensor_orig is tensor_restored}")
# Expected output for last line: False, as 'from_dlpack' creates a new Python Tensor object
# sharing the same underlying data.