This lab shows how to convert data between PyTorch tensors and NumPy arrays using tensor.numpy(), torch.from_numpy(), torch.as_tensor() and torch.tensor(). The main point is memory: the first three can share one buffer, so a change on one side shows up on the other, while torch.tensor() always makes a copy. The sections below the notebook explain those rules, then cover GPU tensors, autograd tensors, dtype problems and the errors you are most likely to see.
Which conversions share memory
The notebook above shows four ways to convert data. They look alike but behave differently. Some return a view of the same memory, so a change on one side shows up on the other. Others make an independent copy. Choosing the wrong one causes bugs that are hard to trace, such as a training batch changing after you have already logged it.
| Call | Direction | Shares memory? | Notes |
|---|---|---|---|
t.numpy() | Tensor to NumPy | Yes (CPU only) | Fails on CUDA tensors and on tensors with requires_grad=True |
torch.from_numpy(a) | NumPy to Tensor | Always | Keeps the NumPy dtype. Fails on arrays with negative strides |
torch.as_tensor(a) | NumPy or list to Tensor | Only if no dtype or device change is needed | Copies when you pass a different dtype or device |
torch.tensor(a) | Anything to Tensor | Never | Always copies and returns a new leaf tensor |
np.asarray(t) | Tensor to NumPy | Yes (CPU, no grad) | Behaves like t.numpy() |
Note: Memory stays shared only through in-place operations such as a[0] = 1, t.add_(1) or a += 1. A line like t = t + 1 creates a new tensor, and after that the two objects are no longer linked.
Prerequisites
- A Python 3 version supported by your PyTorch release. The notebook metadata shows Python 3.7, which current PyTorch releases no longer support.
- PyTorch and NumPy installed in the same environment, for example with
pip install torch numpy. - Jupyter is optional. Every example below also runs as a plain
.pyscript.
python -m venv .venv
source .venv/bin/activate
pip install torch numpy
python -c "import torch, numpy; print(torch.__version__, numpy.__version__)"Code language: JavaScript (javascript)
Runnable script that proves the memory rules
The notebook uses torch.rand, so its output changes on every run. The script below uses fixed values so you can compare your output with the comments. np.shares_memory() lets you check sharing directly instead of inferring it from changed values.
import numpy as np
import torch
# 1. Tensor -> NumPy: shares memory on CPU
t = torch.zeros(2, 3)
a = t.numpy()
a[0, 0] = 100.0
print(t[0, 0].item()) # 100.0
t.add_(1) # in-place change on the tensor side
print(a[0]) # [101. 1. 1.]
# 2. NumPy -> Tensor with from_numpy: shares memory, keeps dtype
arr = np.array([1.0, 2.0, 3.0])
t2 = torch.from_numpy(arr)
arr[0] = -1.0
print(t2) # tensor([-1., 2., 3.], dtype=torch.float64)
# 3. as_tensor: shares only when no conversion is required
x = np.array([4, 8])
same = torch.as_tensor(x)
converted = torch.as_tensor(x, dtype=torch.float32)
x[1] = 5
print(same) # tensor([4, 5])
print(converted) # tensor([4., 8.]) (copy, not updated)
# 4. torch.tensor: always copies
y = np.array([2, 2])
copy = torch.tensor(y)
y[1] = 4
print(copy) # tensor([2, 2])
# 5. Check sharing explicitly
print(np.shares_memory(arr, t2.numpy())) # True
print(np.shares_memory(y, copy.numpy())) # FalseCode language: PHP (php)
Sections 1 and 2 match the first half of the notebook. Section 3 adds the case the notebook leaves out: passing a different dtype to torch.as_tensor() forces a copy, so the tensor stops following the array. Section 4 matches the notebook's last cells.
Note: On Windows with NumPy versions before 2.0, the default integer type is 32-bit. There, same prints as tensor([4, 5], dtype=torch.int32). On Linux and macOS it is int64, which PyTorch does not show in the output.
Converting GPU and autograd tensors to NumPy
NumPy arrays live only in CPU memory and know nothing about autograd. That is why tensor.numpy() refuses two common kinds of tensor. In real training code you will usually have to detach the tensor and move it to the CPU first.
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
w = torch.rand(3, requires_grad=True, device=device)
# w.numpy() raises an error: the tensor requires grad (and may be on the GPU)
w_np = w.detach().cpu().numpy() # standard pattern
print(w_np.dtype, w_np.shape) # float32 (3,)
# Recent PyTorch releases also accept a shortcut that detaches and copies as needed
w_np2 = w.numpy(force=True)Code language: PHP (php)
detach()returns a tensor that shares data withwbut has no gradient history. It does not copy anything.cpu()copies the data to host memory if the tensor is on a GPU. If it is already on the CPU, it returns the same tensor.- Once the data has gone through a GPU, the NumPy array no longer shares memory with the original tensor. Writing to the array has no effect on the model.
- Going the other way,
torch.from_numpy(arr).to("cuda")ortorch.as_tensor(arr, device="cuda")always copies, because the array is in CPU memory.
Watch the dtype: float64 versus float32
NumPy creates float arrays as float64 by default, and torch.from_numpy() keeps that dtype. That is why the notebook shows dtype=torch.float64. PyTorch layers use float32 by default, so feeding them a float64 tensor fails with a dtype mismatch error such as mat1 and mat2 must have the same dtype.
import numpy as np
import torch
features = np.random.rand(8, 4) # float64
model = torch.nn.Linear(4, 1) # float32 weights
# Option 1: convert in NumPy, then share memory
x = torch.from_numpy(features.astype(np.float32))
# Option 2: convert in PyTorch (this makes a copy)
x = torch.from_numpy(features).float()
# Option 3: one call that converts and copies only if needed
x = torch.as_tensor(features, dtype=torch.float32)
print(model(x).shape) # torch.Size([8, 1])Code language: PHP (php)
Integer arrays have the same issue. Labels for nn.CrossEntropyLoss must be int64 (torch.long). Image data loaded as uint8 usually needs .float() and scaling before it goes into a network.
Common errors and how to fix them
| Error message (abridged) | Cause | Fix |
|---|---|---|
can't convert cuda:0 device type tensor to numpy | Calling .numpy() on a GPU tensor | t.cpu().numpy() |
Can't call numpy() on Tensor that requires grad | Tensor is part of the autograd graph | t.detach().numpy() or t.detach().cpu().numpy() |
At least one stride in the given numpy array is negative | Array came from arr[::-1], np.flip() or a similar view | torch.from_numpy(arr.copy()) or np.ascontiguousarray(arr) |
The given NumPy array is not writable (warning) | Array is read-only, for example a view returned by some image libraries | Pass arr.copy(), or use torch.tensor(arr) to copy |
can't convert np.ndarray of type numpy.object_ | Ragged list or mixed types in the array | Pad sequences to one length or build the array with an explicit numeric dtype |
mat1 and mat2 must have the same dtype | float64 input sent to float32 layers | Convert with .float() or astype(np.float32) |
Corrections to the notebook
- The markdown above the
torch.from_numpysharing demo refers totensorandnumpy_from_tensorand says that modifying the original array changes them. The cell actually modifiestensor_from_numpyand shows the change innumpy_arr. Read it as:tensor_from_numpyandnumpy_arrshare memory, so a change to either one is visible in the other. - The heading on the
torch.as_tensorcell only covers input that is already a tensor. For a NumPy array,as_tensoralso shares memory when the dtype and device match. If you request a different dtype or device, it copies. - The claim that NumPy arrays and tensors share memory applies to CPU tensors only. GPU tensors must be copied to the CPU first.
- "Interoperablity" in the first heading should read "Interoperability".
- The notebook kernel targets Python 3.7, which current PyTorch releases no longer support. Use a newer Python 3 version.
Best practices
- Use
torch.from_numpy()when you want zero-copy speed and you control the array's lifetime, for example inside aDataset.__getitem__that builds a new array on every call. - Use
torch.tensor()or.clone()when the source array may be changed later, such as a buffer that gets reused or a preprocessing cache. - To copy an existing tensor, use
t.clone().detach()instead oftorch.tensor(t). PyTorch prints a warning recommending this. - Set the dtype on purpose at the boundary between NumPy and PyTorch, usually
float32for features andint64for class labels. - In evaluation code, convert outputs with
outputs.detach().cpu().numpy()insidetorch.no_grad(), so you do not keep autograd graphs alive. - When behaviour surprises you, check with
np.shares_memory()instead of guessing.
Frequently asked questions
Does tensor.numpy() copy the data?
No. For a CPU tensor, tensor.numpy() returns an array that uses the same memory, so in-place changes on either side show up on the other. Use tensor.numpy().copy() or tensor.clone().numpy() if you need an independent array.
What is the difference between torch.from_numpy and torch.tensor?
torch.from_numpy() always shares memory with the source array and keeps its dtype. torch.tensor() always copies the data, so later changes to the array do not affect the tensor.
When does torch.as_tensor share memory with a NumPy array?
It shares memory when the array's dtype is supported by PyTorch and you do not ask for a different dtype or device. If you pass dtype=torch.float32 for a float64 array, or device='cuda', it creates a copy.
How do I convert a CUDA tensor to a NumPy array?
Move the tensor to the CPU first, and detach it if it requires gradients: t.detach().cpu().numpy(). Recent PyTorch releases also support t.numpy(force=True), which does the same in one call.
Why is my tensor float64 after converting from NumPy?
NumPy float arrays default to float64, and torch.from_numpy() keeps the source dtype. Convert with .float(), arr.astype(np.float32) or torch.as_tensor(arr, dtype=torch.float32) before passing the data to a model.
Related tutorials
- More Machine Learning tutorials
- Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals