pytorch-deep-learning icon indicating copy to clipboard operation
pytorch-deep-learning copied to clipboard

PyTorch and numpy - when converting from tensor to numpy they are mapped to same memory location

Open ashwinshetgaonkar opened this issue 3 years ago • 1 comments
trafficstars

for pytorch version:'1.11.0'

# converting from tensor to numpy
t = torch.ones(7)
np_array = t.numpy()
t , t.dtype , np_array , np_array.dtype

output:

(tensor([1., 1., 1., 1., 1., 1., 1.]),
 torch.float32,
 array([1., 1., 1., 1., 1., 1., 1.], dtype=float32),
 dtype('float32'))

After changing the tensor

# change the tensor see what happens to the numpy array
t += 10
t , t.dtype , np_array , np_array.dtype

output:

(tensor([11., 11., 11., 11., 11., 11., 11.]),
 torch.float32,
 array([11., 11., 11., 11., 11., 11., 11.], dtype=float32),
 dtype('float32'))

ashwinshetgaonkar avatar Aug 04 '22 03:08 ashwinshetgaonkar

according to the TORCH.FROM_NUMPY document(v1.12):

The returned tensor and ndarray share the same memory. Modifications to the tensor will be reflected in the ndarray and vice versa.

drippypale avatar Oct 19 '22 16:10 drippypale