Is there a nice way to to check if numpy array and torch tensor point to same underlying data?
I want to check if numpy array and torch tensor point to same underlying memory.
So far I've came up with a simple check but it doesn't look super elegant.

import numpy as np
import torch

# example 
a = np.random.randn(3,3)
b = torch.from_numpy(a)

assert a.__array_interface__['data'][0] == b.data_ptr()


Is there a nicer way to do it? Also, could some potential undefined/incorrect behaviour occur if using this assertion?

Thanks in advance for the answers :)

This is a completely valid way to access and compare the pointers. The array interface is designed to allow sharing data buffers, so it will have the correct pointer. With that said, if you prefer a less verbose solution, you could also grab it directly like so:

import numpy as np
import torch
​
# example 
a = np.random.randn(3,3)
b = torch.from_numpy(a)
​
print(a.ctypes.data)
print(b.data_ptr())
140413464706720
140413464706720

