NumPy & DLPack Interop
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Data science code often mixes NumPy arrays, pandas frames and PyTorch tensors. Converting between them can be free (the two objects share one buffer) or a full copy, and the difference matters for both speed and correctness. This page covers the NumPy bridge and the DLPack exchange protocol that connects PyTorch to other array libraries and GPU frameworks. It targets Python 3.13, PyTorch 2.15 and NumPy 2.x. Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31; the CuPy example needs a CUDA GPU and CuPy and was not executed. The NumPy side is covered in NumPy interoperability and the shared-array standard in the array API standard.
From NumPy to PyTorch
import numpy as np
import torch
arr = np.arange(6, dtype=np.float32).reshape(2, 3)
t_shared = torch.from_numpy(arr) # shares memory, keeps dtype
t_copy = torch.tensor(arr) # always copies
t_maybe = torch.as_tensor(arr) # shares when it can (same dtype, CPU)
arr[0, 0] = 100.0
print(t_shared[0, 0].item()) # 100.0 (shared)
print(t_copy[0, 0].item()) # 0.0 (copied)
# dtype conversion forces a copy
t64 = torch.as_tensor(arr, dtype=torch.float64)
Details:
-
torch.from_numpyalways shares memory, resizing the tensor is not allowed, and the array must have a supported dtype (for examplefloat32,float64,int64,bool; there is nouint16orobjectsupport in the same way, and unsupported dtypes raiseTypeError). -
NumPy arrays with negative strides are not supported by
from_numpy; make them positive withnp.ascontiguousarrayorarr.copy(). -
A non-writable NumPy array (for example from
np.frombufferon bytes) triggers a warning, because the tensor would be writable while the array is not; copy it first if you intend to write. -
NumPy defaults to
float64while PyTorch models default tofloat32. Feeding afloat64tensor to a float32nn.Linearraises a dtype mismatch, so convert explicitly:torch.from_numpy(arr).float(). -
from_numpyandnumpy()need the CPU. Move to the GPU afterwards with.to(device), which copies.
From PyTorch to NumPy
t = torch.ones(3)
a = t.numpy() # shares memory with t (CPU tensor)
t.add_(1)
print(a) # [2. 2. 2.]
g = torch.ones(3, requires_grad=True)
try:
g.numpy() # RuntimeError: requires grad
except RuntimeError as err:
print("cannot call numpy() on a tensor that requires grad")
a2 = g.detach().numpy() # share data, drop autograd
gpu = torch.ones(3, device="cuda") if torch.cuda.is_available() else torch.ones(3)
a3 = gpu.detach().cpu().numpy() # the standard recipe: detach, then cpu, then numpy
a4 = t.numpy(force=True) # detach + cpu + (copy if needed) in one call
Tensor.numpy(force=False) returns a NumPy array sharing the tensor’s buffer. It raises if the tensor requires grad, is not on the CPU, or has a conjugate or negative bit set; force=True performs the detach, move and resolution for you and copies when needed. Because the buffer is shared, an in-place change on one side shows on the other. Calls like plt.plot(tensor) or np.asarray(tensor) also work on CPU tensors that do not require grad, through the __array__ protocol. Tensor features without NumPy equivalents (bfloat16, quantized tensors, sparse tensors, nested tensors) cannot be converted directly; cast to float32 first.
pandas and scikit-learn
Use torch.from_numpy(df.to_numpy(dtype="float32")) to turn a numeric DataFrame into a tensor, and tensor.numpy() (after detach().cpu()) to feed predictions back to scikit-learn metrics. Mixed-type frames must be encoded first; see Feature Engineering. Wrapping a PyTorch model for scikit-learn pipelines is covered on Using scikit-learn with PyTorch and Keras.
DLPack
DLPack is an open in-memory tensor structure that lets libraries exchange tensors without copying, on the CPU and on GPUs. Besides NumPy (1.22 and later), libraries such as CuPy, JAX, TensorFlow and others implement it. PyTorch exposes it through torch.from_dlpack and torch.utils.dlpack.
import torch
from torch.utils import dlpack
t = torch.arange(6, dtype=torch.float32)
t2 = torch.from_dlpack(t) # any object with __dlpack__ works
t2[:2] = -1
print(t[:3]) # tensor([-1., -1., 2.]) -- same memory
# Exchange with NumPy (CPU) through the protocol, no copy
import numpy as np
arr = np.from_dlpack(t) # NumPy >= 1.22
t3 = torch.from_dlpack(arr)
# Legacy capsule route (single use)
cap = dlpack.to_dlpack(t)
t4 = torch.from_dlpack(cap) # consume the capsule exactly once
Per the official page:
-
torch.from_dlpack(ext_tensor, device=None, copy=None)accepts an object implementing__dlpack__or a DLPack capsule. The result shares memory with the input.deviceselects the target device andcopy=Nonecopies only if necessary. -
Calling
from_dlpackdirectly on the tensor object is the idiomatic route;torch.utils.dlpack.to_dlpackis described as the legacy interface, and its capsule can only be consumed once (reusing it is undefined behaviour). -
ReadOnlyTensorWrapper(tensor)creates a zero-copy, export-only read-only view; other torch operations on the wrapper raise aRuntimeError.
A GPU example moves data between PyTorch and CuPy without touching the host:
import cupy as cp
import torch
x = torch.randn(1000, device="cuda")
c = cp.from_dlpack(x) # CuPy array on the same GPU buffer
c *= 2 # visible through x
y = torch.from_dlpack(c)
Source: https://docs.pytorch.org/docs/stable/dlpack.html and https://docs.cupy.dev/en/stable/user_guide/interoperability.html
Pitfalls: asynchronous GPU work must be ordered between libraries, which the protocol’s stream handshake handles when both sides implement __dlpack__ fully (the PyTorch page does not document a stream argument, so prefer passing objects rather than hand-built capsules); lifetime is tied to the shared buffer, so keep references while using either side; and dtypes without a DLPack equivalent are rejected.
Choosing a route
| Goal | Use | Copies? |
|---|---|---|
NumPy array to tensor, CPU |
|
no |
Tensor to NumPy, CPU |
|
no |
Tensor on GPU to NumPy |
|
yes (device copy) |
PyTorch and CuPy/JAX on one GPU |
|
no |
Need an independent buffer |
|
yes |