Skip to content

Commit 4b05551

Browse files
authored
Check whether the buffer is empty (#468)
Apparently, PyTorch does not handle CUDA array interface well if the tensor is empty. Instead of saying 'failed to convert', it is better to warn users that the buffer is empty, because it is likely not what users intend.
1 parent 9a70d71 commit 4b05551

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

src/spdl/io/_convert.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,15 @@ def to_torch(buffer: CPUBuffer | CUDABuffer):
5151
Returns:
5252
(torch.Tensor): A PyTorch Tensor.
5353
"""
54-
if hasattr(buffer, "__cuda_array_interface__"):
54+
if (interface := getattr(buffer, "__cuda_array_interface__", None)) is not None:
5555
# Note: this is to silence pyre errors.
5656
# Usually, it should be asserting that `buffer` is a CUDABuffer,
5757
# but CUDABuffer class is a stub, so it would fail.
5858
assert not isinstance(buffer, CPUBuffer)
59-
data_ptr = buffer.__cuda_array_interface__["data"][0]
59+
if any(s == 0 for s in interface.get("shape", [])):
60+
raise ValueError("0-element array is not supported.")
61+
62+
data_ptr = interface["data"][0]
6063
tensor = torch.as_tensor(buffer, device=f"cuda:{buffer.device_index}")
6164
if tensor.data_ptr() == 0:
6265
raise RuntimeError(

0 commit comments

Comments
 (0)