How do I find the number of elements taking up memory for an expanded view of a pytorch tensor?
Tensor.expand() returns a new view of an underlying tensor, but doesn't actually allocate more memory for the expanded view.
If I have a tensor that is the result of calling expand() (some unknown number of times), how can I tell how many cells are actually allocated in memory for the tensor (in my actual use-case, I really just care about knowing whether or not that number is 1)?
Is there something like what I'm calling elements_in_memory as used in the following?:
import torch

t = torch.tensor(4.0)
t2 = t.expand(3, 4)
t3 = t2.unsqueeze(0).expand(5, 3, 4)

# I'm looking for something like this (which doesn't work) 
assert t.elements_in_memory == 1
assert t2.elements_in_memory == 1
assert t3.elements_in_memory == 1 


Some things I've tried:

t.data_ptr refers to the first element of the underlying tensor in memory, so t.data_ptr == t2.data_ptr, but that doesn't tell me how many elements.


It looks like t.storage().size() is what I'm after.
From the torch.Tensor documentation:

Each tensor has an associated torch.Storage, which holds its data. The tensor class also provides multi-dimensional, strided view of a storage and defines numeric operations on it.

Tensor.storage() returns a reference to the storage used for the tensor:
import torch

t = torch.tensor(4.0)
t2 = t.expand(3, 4)
t3 = t2.unsqueeze(0).expand(5, 3, 4)

assert t.storage().size() == 1
assert t2.storage().size() == 1
assert t3.storage().size() == 1

t4 = torch.ones(3, 4)
t5 = t4.unsqueeze(0).expand(5, 3, 4)

assert t4.storage().size() == 12
assert t5.storage().size() == 12

Note that the underlying storage might also include more elements than are exposed by some particular view (this wasn't relevant to my use-case).  For example torch.ones(10)[3:6].storage().size() == 10.
