I'm currently using the has_storage()
method to check whether a tensor is empty or not, but I wonder if there is anything better other than this! and whether there are any implications involved in using this other than the fact that an initialized torch::Tensor
always has a storage while an empty one doesn't!
After some digging, it turns out that the best solution for this is to use .numel()
method which returns the number of elements a tensor has.
In summary:
numel()
defined()
and then numel()
Side note:
An empty tensor (that is the one created using torch::Tensor t;
for example) returns zero when .numel()
is used, while the size/sizes will result in an exception.
This is a perfect check for such cases where an empty tensor (in the sense I just explained above) is returned. One can simply do:
if (!tensor.numel())
{
std::cout<<"tensor is empty!" << std::endl;
// do other checks you wish to do
}
reference
Yes there is a small nuance here : all tensors do not have the same underlying implementation, and some implementations will have has_storage
return false
no matter what. This is in particular the case for sparse tensor (see here).
However I am not aware of any better way. Just be sure to correctly track your sparse tensors if you use them (and your opaque tensors, if you ever need whatever they are ^^)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With