Why Your PyTorch Tensor Changes When You Edit the NumPy Array

Wait 5 sec.

Here is a situation that is easy to run into: you load your data into a NumPy array, convert it to a PyTorch tensor for training, and change a few values in the tensor. Later you print the original array and the changes are already there. You never touched the array.Or it happens the other way around. You tweak the array, and a tensor you created earlier quietly changes. Nothing crashes and no warning appears, so the bug usually surfaces much later as strange training results.This article explains what is actually happening, which conversions share memory and which copy, and how to control it.Quick Summarytorch.from_numpy() and tensor.numpy() do not copy data. The tensor and the array share the same memory, so an edit on one side shows up on the other.torch.tensor() always copies. torch.as_tensor() shares memory only when it doesn't need to change the dtype or device.A change of dtype or device silently turns a shared conversion into a copy, so the same code can behave differently depending on your data.Three ways to stay safe: copy at the boundary, use out-of-place operations, or treat shared data as one object with a single owner.What You Expectimport numpy as npimport torchscores = np.array([72, 85, 90, 64])tensor = torch.from_numpy(scores)tensor[0] = 0print(scores)It is natural to expect the original array to stay the same, because the tensor looks like a converted version of it:[72 85 90 64]What Actually Happens[ 0 85 90 64]The array changed, even though the assignment targeted tensor. This is not a bug. It is the documented behavior of torch.from_numpy(): the returned tensor and the array share the same memory, and modifications to one are reflected in the other.Why It Happenstorch.from_numpy() does not convert your data. It creates a second Python object, the tensor, that points at the same block of memory the array already uses.scores (ndarray) ──┐ ├──> one block of memory: [72, 85, 90, 64]tensor (Tensor) ──┘This is a deliberate design choice. Copying a large dataset costs memory and time, and sharing avoids both. The trade-off is that you now have two names for one piece of data, which is the same aliasing problem you meet with Python lists and dictionaries, just spread across two libraries.The same views-versus-copies behavior also exists inside NumPy itself. I covered that side in my article on why a NumPy array changes after preprocessing.It Works in Both DirectionsGoing from a tensor to an array behaves the same way. For a CPU tensor that doesn't require gradients, .numpy() returns an array that shares its storage with the tensor:tensor = torch.ones(3)array = tensor.numpy()array[0] = 5print(tensor.tolist())[5.0, 1.0, 1.0]By default, PyTorch only performs this conversion when sharing is possible: the tensor must be on the CPU, must not require gradients, and must use a dtype NumPy supports. The force=True option relaxes those conditions, and it can return a copy when the tensor can't share its storage, for example when it lives on a GPU.Which Conversions Share Memory?CallShares memory with the source?torch.from_numpy(arr)Yestorch.as_tensor(arr)Yes, if the dtype and device don't change. Otherwise it copies.torch.tensor(arr)No. It always copies.tensor.numpy()Yes, for CPU tensors that don't require gradientstensor.numpy(force=True)Yes when sharing is possible. It may return a copy otherwise.If you only remember one row, remember torch.tensor(). It is the one conversion that never shares data.The dtype Detail That Makes This Hard to DebugSharing is not guaranteed to survive the rest of your code. Tensor.to() returns the tensor itself when it already has the requested dtype and device, and returns a copy when it doesn't. That means a harmless-looking conversion can end the sharing without any error:features = np.array([1.0, 2.0, 3.0]) # float64 by defaultshared = torch.from_numpy(features) # float64, shares memoryconverted = torch.from_numpy(features).to(torch.float32) # float32, a copyshared[0] = 99.0converted[1] = 77.0print(features)[99. 2. 3.]Only the edit made through shared reached the array. The edit made through converted did not, because changing the dtype created a new tensor with its own memory.NumPy creates float64 arrays by default, while PyTorch's default floating-point dtype is float32. In practice, a pipeline that feeds float32 arrays into from_numpy() shares memory, and the same pipeline fed float64 data followed by a float32 conversion does not. Moving a tensor to a GPU copies it for the same reason: the data has to be copied into GPU memory.A Realistic Failure: Normalizing Inside a DatasetThe sharing problem is most expensive when an in-place operation runs repeatedly. Consider a data-loading loop that subtracts a value from each sample every epoch:features = np.array([[10.0, 20.0], [30.0, 40.0]], dtype=np.float32)data = torch.from_numpy(features)for epoch in range(3): batch = data[0] batch -= 5 print(epoch, features[0].tolist())0 [5.0, 15.0]1 [0.0, 10.0]2 [-5.0, 5.0]The adjustment was meant to be applied once per sample, but it is applied again on every epoch. Two things combine here. Basic indexing such as data[0] returns a view of the original tensor in PyTorch, and -= modifies that view in place. Because the tensor shares memory with the array, the NumPy data keeps drifting.Three Ways to Fix ItFix 1: Copy at the boundaryscores = np.array([72, 85, 90, 64])tensor = torch.tensor(scores)tensor[0] = 0print(scores)[72 85 90 64]torch.tensor() copies the data, so the tensor and the array are fully independent. torch.from_numpy(scores.copy()) achieves the same result.Use it when the array must stay pristine: raw data you reuse across experiments, cached features, or arrays that other code holds a reference to. The cost is one extra copy of the data in memory, which matters for very large arrays.Fix 2: Keep the sharing, but avoid in-place operationsfeatures = np.array([[10.0, 20.0], [30.0, 40.0]], dtype=np.float32)data = torch.from_numpy(features)for epoch in range(3): batch = data[0] - 5 print(epoch, features[0].tolist())0 [10.0, 20.0]1 [10.0, 20.0]2 [10.0, 20.0]data[0] - 5 creates a new tensor instead of modifying the existing one, so the source array never changes.Use it when the dataset is large and you want to avoid a full copy. The cost is that every operation allocates a new tensor, and the safety depends on every piece of code that touches the data avoiding in-place operations such as -=, +=, and methods that end in an underscore.Fix 3: Decide who owns the dataSometimes sharing is exactly what you want, for example in a zero-copy pipeline. In that case, treat the array and the tensor as one object. Pick one side as the owner, document it, and mutate through that side only.When you convert back for NumPy, pandas, or plotting code, use tensor.detach().cpu().numpy() and add .copy() if the array will be modified independently:result = tensor.detach().cpu().numpy().copy()Use it when memory is tight and the data flow is simple enough that ownership is clear.How to Check Whether Two Objects Share MemoryWhen you aren't sure, test it instead of guessing:scores = np.array([72, 85, 90, 64])shared = torch.from_numpy(scores)copied = torch.tensor(scores)print(np.shares_memory(scores, shared.numpy()))print(np.shares_memory(scores, copied.numpy()))TrueFalseEdge Cases Worth KnowingRead-only arrays. The PyTorch documentation warns that writing to a tensor created from a read-only NumPy array is not supported and results in undefined behavior. If an array comes from a read-only source, copy it first.Slices stay connected. Basic slicing and indexing on a tensor return views, so tensor[0] or tensor[1:3] still points at the original array's memory.Gradients. tensor.numpy() doesn't convert a tensor that requires gradients by default. Call .detach() first. The detached tensor still shares storage with the original.The Mental Model to RememberA tensor created with from_numpy() is not converted data. It is a second handle on the same memory.Before converting, ask one question: do I need two independent copies of this data, or two ways of looking at one copy? If you need independence, use torch.tensor() or copy explicitly. If you want sharing, keep it deliberate and avoid in-place operations on shared data.The mystery at the start of this article goes away once you stop thinking of the conversion as producing a new array. The scores array changed because it was never separate from the tensor in the first place.