How to create a empty tensor with numel == 0 and data_ptr == nullptr?

I create a empty tensor by at::Tensor tensor = at::empty({}, options.device(kCUDA).dtype(dtype));

but the tensor has attributes like:

tensor.numel() == 1 // true
tensor.data_ptr() == nullptr // false

and I tried with Tensor tensor = at::Tensor().to(dtype).to(kCUDA);, which fails of a Runtime error: tensor does not have a device.

how could I just create a tensor with numel == 0 and data_ptr == nullptr?

What does data_ptr return in your case?
In Python I see 0:

torch.empty(0, device="cuda").data_ptr()
# 0

This is a scalar (and thus 1-element) tensor.
As Piotr mentions, you would want to provide a size-0 dimension to get a 0 element tensor:
at::Tensor tensor = at::empty({0}, options.device(kCUDA).dtype(dtype));

Best regards


1 Like

In my case the data_ptr is just a normal pointer which point to the one-element data, while I expected a nullptr.

Okk, seems the only difference is the shape of {0} instead of {}, I’ll give a try, thx!