Check if tensor_a is view of tensor_b

Was wondering if there is a way to check tensor_a.is_view_of(tensor_b).

parent = torch.arange(4 * 5).view(4, 5)
child1 = parent[[0, 1]]
child2 = parent[:2]
child3 = parent[2:]

child2 and child3 are views of parent because of the slice-style indexing, while child1 is detached. I tried child2.data_ptr() == parent.data_ptr() and this correctly determines that child2 shares memory with parent, but will not work for child3 because of the memory offset (maybe with some pointer arithmetic).

Maybe This thread can help you.

BTW, this snippet works for your case:

import torch
def same_storage(x, y):
	x_ptrs = set(e.data_ptr() for e in x.view(-1))
	y_ptrs = set(e.data_ptr() for e in y.view(-1))
	return (x_ptrs <= y_ptrs) or (y_ptrs <= x_ptrs)

same_storage(parent, child1) # False
same_storage(parent, child2) # True
same_storage(parent, child3) # True