PyTorch tensors: from ndarray to GPU
PyTorch tensors extend NumPy's memory model with devices, deep-learning dtypes and operation tracking for autograd. Learn to manage views and move data between NumPy, CPU and GPU without unnecessary copies or common device and dtype errors.
After this lesson you can
- Create tensors with the correct dtype and device and write device-agnostic code.
- Predict when view, reshape, permute, expand and contiguous share or copy memory using stride() and is_contiguous().
- Share memory between NumPy and PyTorch with from_numpy and numpy(), and understand the GPU and requires_grad limits.
- Distinguish in-place and out-of-place operations and their effects on views and shared memory.
- Translate vectorized NumPy code to PyTorch and measure when a GPU pays off.
Before you start
Motivation: the same line, two machines
On the lab machine (an i9-14900HX and an RTX 4060 Laptop, with PyTorch 2.11), a measurement with float32 matrices gives these figures:
| operation | CPU | GPU |
|---|---|---|
A @ B with | 162 ms | 19 ms |
A @ B with | 11 µs | 24 µs |
torch.exp(x) with elements | 15 µs | 22 µs |
| copy the matrix (64 MiB) from CPU to GPU | 5.7 ms | |
A @ B with in float64 | about 430 GFLOP/s | about 200 GFLOP/s |
The first row sells GPUs: eight times faster without changing a line. The others explain why so many people are disappointed at first. For small matrices the GPU loses, because each operation pays a fixed launch cost of a few microseconds. Data are not magically on the GPU: crossing the PCIe bus costs an appreciable fraction of the computation being accelerated. A consumer GPU computes float64 35 to 45 times slower than float32, even slower than the CPU, so converting a NumPy array without thinking can sink training.
The object behind all this is the PyTorch tensor. You already know most of its memory model because it is the ndarray model: a memory block plus a recipe of shape, strides and offset. It adds three things: a device (CPU or GPU), dtypes designed for deep learning, and the ability to record operations for later differentiation. This lesson turns those differences into rules you can apply without running anything: the dtype resulting from an operation, when GPU transfers pay off, which operations share memory, when view fails and an in-place operation unexpectedly changes something, and how to move between NumPy and PyTorch without unnecessary copies or accidental aliasing.
Anatomy of a tensor
The element at indices is at storage position , the same affine formula studied with NumPy strides with two differences in units: strides and offset count elements rather than bytes, and the byte address is obtained by multiplying by element_size(). The table summarizes the correspondence.
| NumPy | PyTorch | difference |
|---|---|---|
buffer, a.base | t.untyped_storage(), t._base | storage is an object with its own size and device |
a.strides (bytes) | t.stride() (elements) | multiply by t.element_size() |
| pointer to first element | t.storage_offset() | explicit offset, in elements |
| negative strides | do not exist | torch.flip copies; from_numpy(a[::-1]) fails |
np.shares_memory(a, b) | compare untyped_storage().data_ptr() | shared storage, not necessarily shared bytes |
flags.c_contiguous | t.is_contiguous() | size-1 axes do not count in either |
t.device, t.requires_grad, t.grad_fn | new additions |
The cell revisits the same examples as NumPy. It needs PyTorch, so it runs in the local lab; all PyTorch cells in this lesson do.
import time
import numpy as np
import torch
x = torch.arange(12, dtype=torch.float32).reshape(3, 4)
def anatomia(nombre, t, ref=x):
mismo = t.untyped_storage().data_ptr() == ref.untyped_storage().data_ptr()
print(f"{nombre:20s} shape={str(tuple(t.shape)):9s} stride={str(t.stride()):8s} "
f"offset={t.storage_offset():2d} contiguo={t.is_contiguous()!s:5s} storage de x={mismo}")
anatomia("x", x)
anatomia("x.t()", x.t())
anatomia("x[1:, 2:]", x[1:, 2:])
anatomia("x[:, ::2]", x[:, ::2])
anatomia("x[0].expand(3, 4)", x[0].expand(3, 4))
anatomia("x.t().contiguous()", x.t().contiguous())
print("dtype:", x.dtype, "| device:", x.device, "| element_size:", x.element_size(), "B | nbytes:", x.nbytes, "B")
print("storage:", x.untyped_storage().nbytes(), "B | x._base:", tuple(x._base.shape),
"| x.t()._base is x._base:", x.t()._base is x._base)
print("posición de x[2, 1]:", x.storage_offset() + 2 * x.stride(0) + 1 * x.stride(1), "=",
(x[2, 1].data_ptr() - x.data_ptr()) // x.element_size(), "(según el puntero)")
w = torch.ones(3, requires_grad=True)
print("x.requires_grad:", x.requires_grad, "| (w * 2).grad_fn:", (w * 2).grad_fn.name())npm run lab and open the connection link.As in NumPy, x does not own its memory: torch.arange created a 12-element tensor and reshape returned a view of it, x._base. All later views point to that same 48-byte storage. x[0].expand(3, 4) has stride 0 on axis 0: its 12 logical elements read only 4 memory positions. And w * 2 carries the function MulBackward0, the node autograd will use to propagate gradients. A tensor recording operations stores history as well as memory; that is the next lesson’s topic.
dtypes for deep learning
In scientific computing the default type is float64. In deep learning the bottleneck is moving and multiplying billions of numbers, and the default is float32, with 16-bit types wherever tolerable.
| dtype | bits (sign, exponent, mantissa) | maximum | use | |
|---|---|---|---|---|
torch.float64 | 1, 11, 52 | verification, statistics; extremely slow on consumer GPUs | ||
torch.float32 | 1, 8, 23 | default: parameters, optimizer | ||
torch.bfloat16 | 1, 8, 7 | mixed-precision activations and weights | ||
torch.float16 | 1, 5, 10 | mixed precision with loss scaling | ||
torch.int64 (long) | 64 | indices, class labels | ||
torch.int32, torch.uint8 | 32, 8 | counts; raw images | ||
torch.bool | 8 | masks |
bfloat16 deserves a closer look because NumPy lacks it. It is literally the upper 16 bits of float32: the same 8-bit exponent and thus the same range, with only 7 mantissa bits. With 8 bits of precision (including the implicit bit), it exactly represents integers up to , so in bfloat16 , and is stored as . In exchange, it never overflows where float32 does not: a gradient of or activation of fits easily, while float16 turns into infinity and rounds below roughly to zero, half its smallest subnormal. Hence bfloat16 has become the working format for large models and float16 requires loss scaling. Details of floating-point formats appear in numerical methods, and practical autocast use in mixed precision.
Tensor memory is simply . An activation tensor of shape has elements: 96 MiB in float32 and half that in bfloat16. On an 8 GB GPU that factor of 2 decides what fits.
Defaults and promotion: two different worlds
Differences in defaults between NumPy and PyTorch are the most common source of errors when passing data between them:
torch.tensor([1.0])isfloat32(the default dtype,torch.get_default_dtype()), butnp.array([1.0])isfloat64.torch.from_numpyandtorch.as_tensorpreserve the array’s dtype: afloat64array gives afloat64tensor.- Integers are
int64in both, and PyTorch requiresint64in many places:cross_entropyrejectsint32labels withexpected scalar type Long but found Int. /between integers gives floating point in both, butfloat32in PyTorch andfloat64in NumPy.
Type promotion also follows different logic. NumPy 2 decides by types alone, treating Python scalars as weak (NEP 50). PyTorch introduces a second hierarchy: dimensionality.
In practice: a float32 tensor plus a float64 tensor with axes gives float64, but adding a zero-axis float64, an np.float64 or a Python float still gives float32, because the category is unchanged and the tensor with axes takes precedence. An int64 tensor plus 1.5 gives float32: the category rises and the dtype is the default. NumPy gives float64 both with np.float64 and with int64 plus 1.5. Two more details: bfloat16 with float16 gives float32, because neither contains the other; integers overflow silently even when the scalar does not fit the dtype: uint8(200) + 100 gives 44, as in NumPy, but uint8(200) + 300 gives 244 where NumPy 2 raises OverflowError.
print("por defecto:", torch.tensor([1.0]).dtype, torch.tensor([1]).dtype, torch.zeros(2).dtype,
torch.arange(3).dtype, torch.arange(3.0).dtype, torch.randint(0, 9, (2,)).dtype)
print("desde NumPy:", np.array([1.0]).dtype, "->", torch.from_numpy(np.array([1.0])).dtype)
f32 = torch.ones(2)
casos = {
"float32 + tensor float64 (1 eje)": lambda: f32 + torch.ones(2, dtype=torch.float64),
"float32 + tensor float64 (0 ejes)": lambda: f32 + torch.tensor(1.0, dtype=torch.float64),
"float32 + np.float64": lambda: f32 + np.float64(1.0),
"int64 + 1.5": lambda: torch.arange(3) + 1.5,
"int64 + tensor float64 (0 ejes)": lambda: torch.arange(3) + torch.tensor(1.5, dtype=torch.float64),
"int64 / int64": lambda: torch.arange(3) / torch.arange(1, 4),
"bfloat16 + float16": lambda: torch.ones(2, dtype=torch.bfloat16) + torch.ones(2, dtype=torch.float16),
"uint8 200 + 100": lambda: torch.tensor([200], dtype=torch.uint8) + 100,
}
for nombre, f in casos.items():
r = f()
print(f"{nombre:34s} -> {str(r.dtype):15s} {r.tolist()}")
print("NumPy: float32 + np.float64 ->", (np.ones(2, np.float32) + np.float64(1.0)).dtype,
"| int64 + 1.5 ->", (np.arange(3) + 1.5).dtype)
for dt in (torch.float16, torch.bfloat16, torch.float32):
fi = torch.finfo(dt)
print(f"{str(dt):15s} bits={fi.bits:2d} eps={fi.eps:.3g} max={fi.max:.3g} menor normal={fi.tiny:.3g}")
print("bfloat16: 256 + 1 =", (torch.tensor(256.0, dtype=torch.bfloat16) + 1).item(),
"| pi =", torch.tensor(3.14159, dtype=torch.bfloat16).item(),
"| float16(70000) =", torch.tensor(70000.0, dtype=torch.float16).item())
print("(64, 512, 768) en bfloat16:", torch.empty(64, 512, 768, dtype=torch.bfloat16).nbytes / 2**20, "MiB")
if torch.cuda.is_available():
def gflops(dtype, n=2048, rep=5):
a = torch.randn(n, n, device="cuda", dtype=dtype)
a @ a
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(rep):
a @ a
torch.cuda.synchronize()
return 2 * n**3 * rep / (time.perf_counter() - t0) / 1e9
for dt in (torch.float64, torch.float32, torch.bfloat16):
print(f"matmul n = 2048 en GPU, {str(dt):15s} {gflops(dt):8.0f} GFLOP/s")npm run lab and open the connection link.The cell’s final table matters most for performance. On the lab RTX 4060 without other load, it gives around 200 GFLOP/s in float64, 7–9 TFLOP/s in float32, and about 30 TFLOP/s in bfloat16, which uses Tensor Cores. Absolute numbers fall when the machine is busy or the laptop throttles, but ratios hold: float32 is 35–45 times faster than float64, and bfloat16 roughly 3 times faster than float32. By default PyTorch performs float32 matmuls in actual float32 (torch.get_float32_matmul_precision() is "highest"); "high" permits TF32 on Tensor Cores with a 10-bit mantissa, trading some precision for speed.
Devices and the cost of moving
The only exception to the same-device rule is zero-axis CPU tensors, which can be combined with GPU tensors (they are treated as scalars). Everything else fails with a RuntimeError naming both devices, appearing at the first operation mixing them, often far from the line that forgot to move something.
The pattern for code working with or without a GPU has three rules:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # una sola decisión, arriba
modelo = MiModelo().to(device) # Module.to mueve los parámetros EN EL SITIO y devuelve self
x = torch.randn(64, 784, device=device) # crea directamente en el dispositivo: sin copia
lote = lote.to(device, non_blocking=True) # Tensor.to devuelve OTRO tensor: hay que reasignar
ruido = torch.randn_like(x) # *_like y x.new_zeros(...) heredan dtype y dispositivo
The asymmetry between the second and fourth lines causes real errors: modelo.to(device) works without assignment because an nn.Module is modified in place, but lote.to(device) without assignment does nothing useful. Creation functions with device= avoid creating a CPU tensor only to copy it later. In recent versions, torch.accelerator.current_accelerator() generalizes the first line to other accelerators.
Asynchronous execution: who waits for whom
When Python executes y = a @ b with GPU tensors, it does not wait for multiplication to finish: it queues the kernel on a CUDA stream and continues. The CPU queues work ahead and the GPU consumes it in order. This asynchrony lets the CPU prepare the next batch while the GPU multiplies. It breaks when the CPU needs a value on the GPU: t.item(), t.tolist(), t.cpu(), print(t), if t > 0: (which calls bool), and operations whose output size depends on data, such as torch.nonzero or Boolean-mask indexing. Each is a synchronization point: the CPU waits for the GPU to empty the queue.
One .item() per step to log loss looks harmless, and is if the GPU is already behind the CPU. But if each step combines CPU work (data preparation) and GPU work (computation), synchronization makes step time the sum of the two rather than their maximum. Instead, accumulate on the GPU and synchronize once every many steps. Asynchronous execution is studied in depth later; this cell makes it visible and also measures copy bandwidth with pageable and pinned memory.
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("dispositivo:", device)
modelo = torch.nn.Linear(4, 2).to(device)
lote = torch.randn(8, 4) # nace en la CPU
for intento in ("sin mover", "con .to(device)"):
try:
y = modelo(lote if intento == "sin mover" else lote.to(device))
print(f"{intento:16s} ok: {tuple(y.shape)} en {y.device}")
except RuntimeError as e:
print(f"{intento:16s} RuntimeError: {str(e)[:88]}...")
print("escalar de 0 ejes en CPU por tensor en GPU ->", (torch.ones(2, device=device) * torch.tensor(3.0)).device)
t = torch.ones(2, device=device)
print("t.to(device) is t:", t.to(device) is t)
if device.type == "cuda":
def medir(f, rep=20):
f(); torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(rep):
f()
torch.cuda.synchronize()
return (time.perf_counter() - t0) / rep
for mb in (1, 16, 64):
a = torch.empty(mb * 2**20 // 4)
p = a.pin_memory()
t_pag = medir(lambda: a.to(device))
t_pin = medir(lambda: p.to(device, non_blocking=True))
print(f"{mb:3d} MiB CPU -> GPU: paginable {a.nbytes / t_pag / 1e9:5.1f} GB/s, fijada {a.nbytes / t_pin / 1e9:5.1f} GB/s")
rng = np.random.default_rng(0)
W = torch.randn(2048, 2048, device=device) / 45
def trabajo_cpu(): # preparar el siguiente lote: unos 2 ms de CPU
return np.sort(rng.random(150_000)).astype(np.float32)
def entrenar(sincronizar, pasos=60):
torch.manual_seed(0) # el mismo punto de partida en las dos versiones
h = torch.randn(2048, 2048, device=device)
perdidas = []
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(pasos):
trabajo_cpu()
h = torch.tanh(h @ W) # unos 2.5 ms de GPU
p = h.pow(2).mean()
perdidas.append(p.item() if sincronizar else p.detach())
total = sum(perdidas) if sincronizar else torch.stack(perdidas).sum().item()
return (time.perf_counter() - t0) / pasos * 1e3, total
entrenar(False, 5)
(t_item, s1), (t_acum, s2) = entrenar(True), entrenar(False)
print(f"con .item() en cada paso: {t_item:.1f} ms/paso; acumulando en la GPU: {t_acum:.1f} ms/paso;"
f" misma suma: {abs(s1 - s2) < 1e-4 * abs(s1)}")npm run lab and open the connection link.With pageable memory, the driver must first copy to an intermediate pinned buffer, reducing bandwidth; with pinned memory, DMA copies directly at about 12 GB/s on this laptop (PCIe 4.0 with 8 lanes, theoretical 15.75 GB/s) and with non_blocking=True does not even block the CPU. That is what pin_memory=True does in the DataLoader. In the loop, .item() per step adds the CPU’s two milliseconds to the GPU’s two and a half; accumulating on GPU lets the CPU prepare the next step during GPU computation, making step time approach the larger of the two. On the unloaded lab machine the results are about 5 ms versus 3 ms; under load both rise, but the difference persists.
A cost model: when does the GPU pay off?
The motivation’s figures allow a small model predicting the crossover. Consider chained operations on float32 matrices, either products X = X @ W or an elementwise function such as X = torch.tanh(X). Let and be sustained CPU and GPU matmul FLOP/s, CPU overhead per operation, GPU kernel launch cost, PCIe bandwidth, and fixed latency per copy. A product costs operations and each matrix occupies bytes. Then
where if data are already on GPU (the Spanish label denotes copy time), if and are uploaded initially and downloaded at the end, and of order if goes up and down each step. For elementwise operations, the computation term is memory traffic, bytes (read and write), divided by each device’s memory bandwidth.
Proof
With , dividing by gives , or . Both sides are positive by assumption and the left increases in , giving threshold . If goes up and down each step, add per step to the GPU side; for large the highest-order terms dominate, , giving . For elementwise operations with a copy each step, the GPU pays at least for PCIe bytes and a launch, , while the CPU pays . If , each GPU term exceeds its CPU counterpart (the second by ): the copy and launch alone are slower than the entire CPU step.
∎With lab measurements GFLOP/s, TFLOP/s, µs and µs, we get , consistent with the opening table (CPU wins at and loses at ). With copies every step and GB/s, the crossover rises to several hundred. Behind the proposition is arithmetic intensity: a product performs operations on bytes, operations per byte, and the larger that ratio, the easier it is to amortize the bus. An elementwise function does one operation per eight bytes and amortizes nothing.
float32 matrices on CPU and GPU, according to this section's model with lab-measured parameters. The green band marks sizes where GPU wins, and bars break its time down into PCIe copies, launches and computation. Start with one matmul copied round-trip: GPU loses. Raise to 100 and watch the crossover approach the resident-data case. Then switch to tanh with copies each step: is there any where GPU wins? Use ‘Adjust hardware’ to enter the lesson lab's printed figures.What you should have seen:
- An isolated operation rarely pays off. With and round-trip copies, the matmul crossover is around , and below that most GPU time is copying. The dashed GPU-without-copies curve shows the bus cost.
- Chaining operations amortizes copies. With , two copies are spread across a hundred products and crossover falls to , nearly the proposition’s . Models are therefore uploaded once and data stay on GPU throughout the training step.
- Copying each step is fatal for low-compute work. With
tanhand copies each step there is no crossover: the 11 GB/s bus is slower than CPU memory. This is the error of calling.cpu()or.numpy()on activations inside the loop. - Small matrices lose to launch overhead. With resident data and , GPU computation lasts nanoseconds and the time is the 12 µs per launch. Give each kernel more work: larger batches, batched operations such as
torch.bmminstead of Python loops, or operation fusion.
The model ignores much (kernel efficiency on medium matrices, caches, variable laptop frequency) and gets the order of magnitude and crossover, not the fine curve: at it predicts 50 µs on GPU and the lab measures about 100 µs. It is a toy version of the roofline model. The next cell, running in the browser, reproduces the interactive’s crossover table.
import numpy as np
HW = dict(p_cpu=900e9, p_gpu=7e12, bw_cpu=60e9, bw_gpu=220e9, pcie=11e9, lanz=12e-6, o_cpu=3e-6, lat=15e-6)
def costes(n, k, op, copias, hw=HW):
b, flops = 4 * n * n, 2 * n**3
t_cpu = k * (hw["o_cpu"] + (flops / hw["p_cpu"] if op == "matmul" else 2 * b / hw["bw_cpu"]))
calc = flops / hw["p_gpu"] if op == "matmul" else 2 * b / hw["bw_gpu"]
copia = lambda nb: hw["lat"] + nb / hw["pcie"]
if copias == "al principio y al final":
t_cop = copia(2 * b if op == "matmul" else b) + copia(b)
elif copias == "en cada paso":
t_cop = (copia(b) if op == "matmul" else 0) + 2 * k * copia(b)
else:
t_cop = 0.0
return t_cpu, t_cop + k * (hw["lanz"] + calc)
def cruce(k, op, copias):
ns = 2.0 ** np.arange(13, 3.999, -0.01) # de n = 8192 hacia abajo
gana = [costes(n, k, op, copias)[1] < costes(n, k, op, copias)[0] for n in ns]
if not gana[0]:
return None
i = gana.index(False) if False in gana else len(ns)
return ns[i - 1]
n_star = ((HW["lanz"] - HW["o_cpu"]) / (2 * (1 / HW["p_cpu"] - 1 / HW["p_gpu"]))) ** (1 / 3)
print(f"n* de la proposición (datos en la GPU): {n_star:.1f}\n")
print(f"{'operación':10s} {'copias':26s} {'k=1':>6s} {'k=10':>6s} {'k=100':>6s} {'k=1000':>6s}")
for op in ("matmul", "tanh"):
for copias in ("al principio y al final", "en cada paso", "ya en la GPU"):
fila = [cruce(k, op, copias) for k in (1, 10, 100, 1000)]
print(f"{op:10s} {copias:26s} " + " ".join(f"{'no hay' if c is None else round(c):>6}" for c in fila))Views, contiguity and in-place operations
Everything you know about NumPy views and copies applies to tensors. PyTorch separates into different methods what NumPy combines, and treats in-place writes as first-class operations with their own naming convention.
view accepts a new shape exactly when the reshape-as-view theorem permits it: grouping axes into blocks with common products, each merged block of old axes must satisfy . PyTorch’s deciding function, computeStride, is the one we translate below. This produces PyTorch’s most famous error: after transpose or permute, two axes larger than 1 that were in C order have strides , and merging them would require . reshape does not fail: it calls view if possible and contiguous().view(...) otherwise, implicitly copying.
x = torch.arange(12.).reshape(3, 4). Each operation creates a tensor derived from the selected one with the metadata PyTorch would give; each card's border color identifies its storage. Below are the selected tensor's logical shape and storage: each cell's color is its source row in x, the triangle marks storage_offset, and the badge counts logical elements reading that position. Start with y = x.t(): request view(12) then reshape(12). Next try x[0] followed by expand and add_(100), and add_(100) on a slice of x: what else changes?What you should have seen:
viewfails wherereshapecopies, for the same reason. Ony = x.t(), with strides ,view(12)raisesRuntimeErrorandreshape(12)creates new storage (a different-colored card). In contrastview(2, 2, 3)works: it only splits the size-4 axis.expandcopies nothing.x[0].expand(2, 4)has strides and the badges show each storage position appears twice. Anadd_on it fails withmore than one element of the written-to tensor refers to a single memory location: if allowed, each position would receive the addition twice.- In-place operations propagate throughout the family. An
add_(100)onx[..., 1:]also changesx,yand every view reading those positions (magenta-bordered cards), and the_versioncounter shared by the family increases. A copy remains unaffected. clonepreserves layout,contiguousdoes not. The clone ofx.t()has its own data but the same strides : it is still noncontiguous.contiguous()reorders into C order and returns the same object on an already contiguous tensor.- NumPy writes behind autograd’s back.
.numpy()shares memory and+= 100on the ndarray changes tensors, but the version counter does not move.
The _version counter deserves explanation. A base tensor and all its views share one version counter, incremented by every PyTorch in-place operation on any of them (it does not belong to storage: two from_numpy calls on the same array share bytes but not a counter). When autograd saves a tensor for backward, it records the version; if it changed when differentiating, it raises one of the variables needed for gradient computation has been modified by an inplace operation. That is why in-place operations require care in differentiated code and x.add_(1) on a leaf with requires_grad=True is forbidden outright. See the autograd lesson. A NumPy write bypasses PyTorch and the counter does not notice: the gradient would silently be wrong.
Internal overlap: what PyTorch checks and what it does not
The expand with add_ error comes from a specific check, has_internal_overlap, with three answers. It returns no if the tensor is dense and nonoverlapping (its sorted strides are those of a contiguous tensor with permuted axes), yes if an axis larger than 1 has stride 0, and too hard otherwise; only yes blocks writing. Deciding generally whether distinct indices reach the same position means finding a nonzero integer vector with and , a knapsack-family problem NumPy solves with np.shares_memory and PyTorch chooses not to solve. torch.as_strided can create overlaps passing the check: torch.as_strided(torch.zeros(5), (3, 3), (1, 1)).add_(1) raises no error and leaves [1, 2, 3, 2, 1] in storage. There is, however, a simple sufficient condition to rule overlap out.
Step 1 of 4. Which axis should we examine?
From scratch: view metadata
To fix the rules, implement them on pure metadata: a class storing only shape, strides and offset and reproducing transpose, permute, unsqueeze, expand, stepped slicing, is_contiguous and view. The last is a literal translation of at::detail::computeStride, PyTorch’s function deciding whether a view exists: it traverses old axes inside out, detects where each mergeable block ends, and distributes each block among new axes.
from dataclasses import dataclass
from math import prod
import random
@dataclass(frozen=True)
class Meta:
"""Solo metadatos: forma, strides en elementos y offset. Sin datos."""
shape: tuple
stride: tuple
offset: int = 0
@staticmethod
def contiguo(shape):
stride, acc = [], 1
for n in reversed(shape):
stride.append(acc)
acc *= n
return Meta(tuple(shape), tuple(reversed(stride)))
def is_contiguous(self):
z = 1
for n, s in zip(reversed(self.shape), reversed(self.stride)):
if n != 1:
if s != z:
return False
z *= n
return True
def permute(self, *dims):
return Meta(tuple(self.shape[d] for d in dims), tuple(self.stride[d] for d in dims), self.offset)
def transpose(self, i, j):
dims = list(range(len(self.shape)))
dims[i], dims[j] = j, i
return self.permute(*dims)
def unsqueeze(self, d):
s = self.shape[d] * self.stride[d] if d < len(self.shape) else 1
return Meta(self.shape[:d] + (1,) + self.shape[d:], self.stride[:d] + (s,) + self.stride[d:], self.offset)
def expand(self, *shape):
lead, st = len(shape) - len(self.shape), []
for i in range(len(shape) - 1, -1, -1): # como inferExpandGeometry, de dentro afuera
n, s = (self.shape[i - lead], self.stride[i - lead]) if i >= lead else (1, shape[i + 1] * st[0])
st.insert(0, s if n == shape[i] else 0) # eje estirado: stride 0
return Meta(tuple(shape), tuple(st), self.offset)
def step_last(self, p): # t[..., ::p]
sh, st = list(self.shape), list(self.stride)
sh[-1], st[-1] = -(-sh[-1] // p), st[-1] * p
return Meta(tuple(sh), tuple(st), self.offset)
def view(self, *new):
"""Traducción de at::detail::computeStride: la vista, o None si no existe."""
assert prod(new) == prod(self.shape), "número de elementos distinto"
out, vd = [0] * len(new), len(new) - 1
base, t_numel, v_numel = self.stride[-1], 1, 1
for td in range(len(self.shape) - 1, -1, -1):
t_numel *= self.shape[td]
fin_de_bloque = td == 0 or (self.shape[td - 1] != 1 and self.stride[td - 1] != t_numel * base)
if fin_de_bloque:
while vd >= 0 and (v_numel < t_numel or new[vd] == 1):
out[vd] = v_numel * base
v_numel *= new[vd]
vd -= 1
if v_numel != t_numel:
return None
if td > 0:
base, t_numel, v_numel = self.stride[td - 1], 1, 1
return Meta(tuple(new), tuple(out), self.offset) if vd == -1 else None
def solape_seguro(self):
"""has_internal_overlap == YES: algún eje de tamaño > 1 con stride 0."""
return any(n > 1 and s == 0 for n, s in zip(self.shape, self.stride))
m = Meta.contiguo((2, 3, 4))
print("permute(2, 0, 1).view(4, 6): ", m.permute(2, 0, 1).view(4, 6))
print("permute(0, 2, 1).view(2, 12): ", m.permute(0, 2, 1).view(2, 12))
print("transpose(1, 2).view(2, 2, 2, 3):", m.transpose(1, 2).view(2, 2, 2, 3))
e = Meta((2, 1, 4), (12, 4, 1)).expand(2, 3, 4) # x[:, :1].expand(2, 3, 4)
print("[:, :1].expand(2, 3, 4): ", e, "| in-place prohibido:", e.solape_seguro())npm run lab and open the connection link.The first line is surprising: permute(2, 0, 1) followed by view(4, 6) works because the two merged axes, sizes and strides , remain in relative C order (). What matters is whether the axes being merged were reordered relative to each other. The second merges axes with strides and fails. Now compare with PyTorch over thousands of random operation chains.
def factorizaciones(n, maxd=4):
out = []
def rec(rem, cur):
if rem == 1:
out.append(tuple(cur))
return
if len(cur) < maxd:
for d in range(2, rem + 1):
if rem % d == 0:
rec(rem // d, cur + [d])
rec(n, [])
return out or [(1,)]
random.seed(0)
fallos, vistas, n_casos = 0, 0, 3000
for _ in range(n_casos):
shape = tuple(random.randint(1, 4) for _ in range(random.randint(1, 3)))
t, mt = torch.empty(shape), Meta.contiguo(shape)
for _ in range(random.randint(0, 4)):
op = random.randrange(4)
if op == 0 and t.dim() >= 2:
i, j = random.sample(range(t.dim()), 2)
t, mt = t.transpose(i, j), mt.transpose(i, j)
elif op == 1 and t.shape[-1] > 1:
t, mt = t[..., ::2], mt.step_last(2)
elif op == 2 and t.dim() < 4:
d = random.randint(0, t.dim())
t, mt = t.unsqueeze(d), mt.unsqueeze(d)
elif op == 3 and t.dim() < 4: # estira los ejes de tamaño 1 y quizá añade uno delante
new = (random.randint(1, 3),) * random.randint(0, 1) + tuple(random.randint(2, 3) if n == 1 else n for n in t.shape)
t, mt = t.expand(*new), mt.expand(*new)
new = random.choice(factorizaciones(t.numel()))
try:
real = t.view(new).stride()
except RuntimeError:
real = None
mia = mt.view(*new)
ok = ((mt.shape, mt.stride) == (tuple(t.shape), t.stride())
and mt.is_contiguous() == t.is_contiguous()
and (mia.stride if mia else None) == real)
fallos += not ok
vistas += real is not None
print(f"{n_casos} cadenas aleatorias: {fallos} discrepancias con PyTorch;"
f" view posible en {vistas}, imposible en {n_casos - vistas}")npm run lab and open the connection link.Zero discrepancies: metadata, contiguity and the view decision match PyTorch in every case, including size-1 axes and expand’s zero strides. With this class in mind, any operation chain can be reasoned about without running it.
NumPy and PyTorch without unnecessary copies
Because a CPU tensor and an ndarray have the same structure, they can share memory. This NumPy and PyTorch interoperability allows loading data with NumPy and training with PyTorch without duplicating gigabytes of memory, but also produces aliasing that is difficult to debug.
| conversion | copy? | dtype | notes |
|---|---|---|---|
torch.from_numpy(a) | never | a’s | fails with negative strides; warns if a is read-only |
torch.as_tensor(a) | only if needed | a’s or requested | copies if dtype changes or another device is requested |
torch.tensor(a) | always | a’s | safe way to make an independent copy |
t.numpy() | never | t’s | TypeError on GPU, RuntimeError with requires_grad, TypeError with bfloat16 |
t.detach().cpu().numpy() | only if t is on GPU | t’s | on CPU, .cpu() returns the same tensor and shares |
t.numpy(force=True) | if needed | t’s | equivalent to detach().cpu()...numpy() |
torch.from_dlpack(x), np.from_dlpack(t) | never | DLPack protocol: also between GPU libraries (CuPy, JAX) |
Two practical consequences. First, dtype: a NumPy dataset is often float64, torch.from_numpy preserves it, and the first nn.Linear raises mat1 and mat2 must have the same dtype, but got Double and Float. The right solution is to convert once, torch.from_numpy(X).float() or torch.as_tensor(X, dtype=torch.float32), which copies; converting the model to double() instead makes all training use float64. Second, aliasing: the idiom t.detach().cpu().numpy(), often assumed always to copy, returns an array sharing memory with t on CPU. Writing to it changes the tensor without the version counter recording it.
import warnings
def comparten(t, a):
return t.device.type == "cpu" and np.shares_memory(t.numpy(), a)
a = np.arange(6, dtype=np.float64)
conversiones = {
"torch.from_numpy(a)": lambda: torch.from_numpy(a),
"torch.as_tensor(a)": lambda: torch.as_tensor(a),
"torch.as_tensor(a, dtype=torch.float32)": lambda: torch.as_tensor(a, dtype=torch.float32),
"torch.tensor(a)": lambda: torch.tensor(a),
"torch.from_numpy(a).float()": lambda: torch.from_numpy(a).float(),
"torch.from_numpy(a[::2])": lambda: torch.from_numpy(a[::2]),
}
if torch.cuda.is_available():
conversiones["torch.as_tensor(a, device='cuda')"] = lambda: torch.as_tensor(a, device="cuda")
for nombre, f in conversiones.items():
t = f()
print(f"{nombre:40s} dtype={str(t.dtype):14s} comparte memoria con a: {comparten(t, a)}")
t = torch.from_numpy(a)
v = t[1:4] # vista del tensor, que a su vez comparte memoria con a
v.mul_(10) # in-place sobre la vista...
print("\na tras v.mul_(10):", a) # ...cambia el array de NumPy
a[0] = -1.0 # y escribir en NumPy cambia el tensor
print("t[0] tras a[0] = -1:", t[0].item(), "| t._version:", t._version, "(el mul_ cuenta; la escritura de NumPy, no)")
pruebas = {
"tensor en GPU .numpy()": lambda: torch.ones(2, device="cuda").numpy(),
"requires_grad .numpy()": lambda: torch.ones(2, requires_grad=True).numpy(),
"bfloat16 .numpy()": lambda: torch.ones(2, dtype=torch.bfloat16).numpy(),
"from_numpy(a[::-1])": lambda: torch.from_numpy(a[::-1]),
}
for nombre, f in pruebas.items():
try:
f()
print(f"{nombre:24s} funciona")
except (TypeError, RuntimeError, ValueError, AssertionError) as e:
print(f"{nombre:24s} {type(e).__name__}: {str(e)[:72]}...")
p = torch.ones(3, requires_grad=True)
n = p.detach().cpu().numpy() # en CPU, .cpu() no copia: n comparte memoria con p
n[0] = 42.0
print("\np tras escribir en n:", p.detach().tolist())
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
torch.from_numpy(np.broadcast_to(np.zeros(3), (2, 3)))
print("from_numpy de un array de solo lectura avisa:", str(w[0].message)[:60], "...")npm run lab and open the connection link.The cell’s table realizes the one above: from_numpy and as_tensor without dtype changes share memory, anything converting dtype or device copies, and torch.from_numpy(a[::2]) shares with stride 2 because positive strides are fine. The next four tests fail with messages worth recognizing immediately. The last line is the real trap: writing to n changed parameter p.
Translating NumPy to PyTorch
Vectorization, broadcasting and gather and scatter work the same in PyTorch. What changes are names, defaults and a few semantic details that silently produce different results.
| NumPy | PyTorch | beware |
|---|---|---|
axis=, keepdims=True | dim=, keepdim=True | |
a.astype(np.float32), a.copy() | t.float() or t.to(torch.float32), t.clone() | t.to does not copy if already the requested dtype |
np.concatenate, np.stack | torch.cat, torch.stack | |
a.T with 3 or more axes (reverses all) | t.permute(*range(t.ndim - 1, -1, -1)) | t.T with more than 2 axes is deprecated; t.mT transposes only the last two, like np.swapaxes(a, -1, -2) |
a.std(), a.var() | t.std(correction=0), t.var(correction=0) | PyTorch uses by default |
np.median (mean of middle values) | t.median() (smaller middle value) | differ with an even number of elements |
a.max(axis=1) | t.max(dim=1) | PyTorch returns (values, indices) |
np.take_along_axis, np.add.at | torch.gather, index_add_ / scatter_add_ | int64 indices |
np.argpartition + take_along_axis | torch.topk | returns sorted values and indices |
np.einsum | torch.einsum | same notation, from the einsum lesson |
np.random.default_rng(0) | torch.Generator().manual_seed(0) | per-device generators |
np.allclose | torch.testing.assert_close | default tolerances depend on dtype |
The standard deviation row causes the most silently wrong results: for , NumPy gives and PyTorch . With these rules, porting the small numerical library you have built is mechanical. The four functions below come from the broadcasting and indexing lessons, written without naming a device: they work on CPU or GPU according to their arguments. They are checked against NumPy versions with torch.testing.assert_close, which selects dtype-appropriate tolerances; tolerance-based assertions are covered in the testing lesson.
from torch.testing import assert_close
def pairwise_sq_dists(X, Y):
"""D[i, j] = |x_i - y_j|^2 con la identidad del producto escalar, recortada a >= 0."""
D = (X * X).sum(dim=1, keepdim=True) + (Y * Y).sum(dim=1) - 2 * X @ Y.T
return D.clamp_min_(0)
def softmax(z, dim=-1):
z = z - z.amax(dim=dim, keepdim=True)
e = z.exp()
return e / e.sum(dim=dim, keepdim=True)
def topk(x, k, dim=-1):
return torch.topk(x, k, dim=dim) # valores e índices, ordenados
def aceleraciones(pos, masa, eps2=1e-2):
d = pos[None, :, :] - pos[:, None, :] # (N, N, 2): d[i, j] = x_j - x_i
r2 = (d * d).sum(dim=-1) + eps2
w = masa[None, :] / (r2 * r2.sqrt())
w.fill_diagonal_(0.0)
return (w[:, :, None] * d).sum(dim=1)
# referencias en NumPy, en float64
def np_dists(X, Y):
return np.maximum((X * X).sum(1)[:, None] + (Y * Y).sum(1) - 2 * X @ Y.T, 0)
def np_softmax(z):
e = np.exp(z - z.max(axis=-1, keepdims=True))
return e / e.sum(axis=-1, keepdims=True)
def np_acel(pos, masa, eps2=1e-2):
d = pos[None] - pos[:, None]
r2 = (d * d).sum(-1) + eps2
w = masa[None] / (r2 * np.sqrt(r2))
np.fill_diagonal(w, 0.0)
return (w[:, :, None] * d).sum(1)
rng = np.random.default_rng(0)
X, Y = rng.standard_normal((300, 16)), rng.standard_normal((200, 16))
Z = 30 * rng.standard_normal((50, 1000))
pos, masa = rng.standard_normal((256, 2)), np.full(256, 1 / 256)
for dev in ["cpu"] + (["cuda"] if torch.cuda.is_available() else []):
T = lambda arr: torch.as_tensor(arr, dtype=torch.float32, device=dev) # float32: el dtype de trabajo
ref = lambda arr: torch.from_numpy(np.ascontiguousarray(arr)).float()
assert_close(pairwise_sq_dists(T(X), T(Y)).cpu(), ref(np_dists(X, Y)), rtol=1e-4, atol=1e-4)
assert_close(softmax(T(Z)).cpu(), ref(np_softmax(Z)))
assert_close(topk(T(Z), 5).values.cpu(), ref(np.sort(Z, axis=1)[:, ::-1][:, :5]))
assert_close(aceleraciones(T(pos), T(masa)).cpu(), ref(np_acel(pos, masa)), rtol=1e-4, atol=1e-5)
print(f"{dev}: las cuatro funciones coinciden con NumPy dentro de las tolerancias de float32")
print("std de [1, 2, 3, 4]: NumPy", round(float(np.std([1.0, 2, 3, 4])), 4),
"| PyTorch", round(torch.tensor([1.0, 2, 3, 4]).std().item(), 4))npm run lab and open the connection link.Distances need explicit tolerances because the identity loses digits through cancellation, especially in float32. It remains to measure, with the N-body simulation, how much GPU gains and how much is lost if each step copies data round-trip. The last line prints your machine’s parameters for the cost-model interactive.
def cronometro(f, rep=5):
"""Mejor de rep repeticiones; sincroniza la GPU antes y después de cada una."""
sync = torch.cuda.synchronize if torch.cuda.is_available() else (lambda: None)
f(); sync()
mejor = float("inf")
for _ in range(rep):
t0 = time.perf_counter()
f(); sync()
mejor = min(mejor, time.perf_counter() - t0)
return mejor
if torch.cuda.is_available():
print(f"{'N':>6s} {'CPU':>10s} {'GPU':>10s} {'GPU + copias':>13s}")
for N in (32, 256, 2048, 4096):
p_c = torch.as_tensor(rng.standard_normal((N, 2)), dtype=torch.float32)
m_c = torch.full((N,), 1 / N)
p_g, m_g = p_c.cuda(), m_c.cuda()
t_cpu = cronometro(lambda: aceleraciones(p_c, m_c))
t_gpu = cronometro(lambda: aceleraciones(p_g, m_g))
t_ida = cronometro(lambda: aceleraciones(p_c.cuda(), m_c.cuda()).cpu())
print(f"{N:6d} {t_cpu * 1e3:7.2f} ms {t_gpu * 1e3:7.2f} ms {t_ida * 1e3:10.2f} ms")
n = 2048
A_c = torch.randn(n, n); A_g = A_c.cuda()
p_cpu = 2 * n**3 / cronometro(lambda: A_c @ A_c) / 1e9
p_gpu = 2 * n**3 / cronometro(lambda: A_g @ A_g) / 1e12
B_c = torch.randn(4 * n * n); B_g = B_c.cuda()
bw_cpu = 2 * B_c.nbytes / cronometro(lambda: torch.tanh(B_c)) / 1e9
bw_gpu = 2 * B_g.nbytes / cronometro(lambda: torch.tanh(B_g)) / 1e9
fijada = A_c.pin_memory()
pcie = A_c.nbytes / cronometro(lambda: fijada.to("cuda", non_blocking=True)) / 1e9
uno = torch.ones(1, device="cuda")
lanz = cronometro(lambda: [uno.add_(1) for _ in range(1000)], rep=3) / 1000 * 1e6
print(f"\nTus parámetros: CPU {p_cpu:.0f} GFLOP/s, GPU {p_gpu:.1f} TFLOP/s, memoria CPU {bw_cpu:.0f} GB/s,"
f" memoria GPU {bw_gpu:.0f} GB/s, PCIe {pcie:.1f} GB/s, lanzamiento {lanz:.1f} µs")npm run lab and open the connection link.The table follows the model. With a few dozen bodies the CPU wins: each step is around ten tiny kernels and the GPU pays launch overhead. With thousands, the GPU is over ten times faster. The copies column shows that for computation on data the bus matters little, because arithmetic intensity grows with . Measurement uses torch.cuda.synchronize before stopping the clock: without it you would time kernel enqueueing, not execution, a classic benchmarking methodology error.
Common mistakes
Exercises
x = torch.arange(24.).reshape(2, 3, 4), with strides . Which statements are true? More than one may apply.More than one answer may be correct.
to_device(batch, device), returning a structure of the same shape as batch with every tensor moved using .to(device). Recursively traverse dictionaries, lists, tuples (preserving their type, including namedtuple) and dataclasses (returning a new instance of the same class, even if frozen), and return all other values unchanged as the same object: strings, numbers, None... Do not modify the original structure. Tests use PyTorch's meta device, whose tensors have no data, so no GPU is needed.import dataclasses
import torch
def to_device(batch, device):
# recorre la estructura y mueve cada tensor
return batchbfloat16 tensor of shape occupy?torch.tensor([1.0]), np.array([1.0]) and torch.from_numpy(np.array([1.0])) have, and what is the consequence for training a model with float32 parameters?More than one answer may be correct.
uint8 image batch of shape goes to GPU over PCIe at 12 GB/s ( bytes/s). How many copy milliseconds per batch are saved by transferring as uint8 and converting to float32 on GPU, instead of converting on CPU and transferring float32? Ignore latency.Summary
- Anatomy. Shareable storage, dtype, device, shape, strides in elements,
storage_offsetand autograd state. No negative strides. Views share storage and version counter. - dtypes.
float32by default,int64for indices,bfloat16(float32range, 8 bits of precision) andfloat16(small range) for mixed precision,float64rarely on consumer GPUs. Promotion considers whether operands have axes: a scalar or zero-axis tensor does not raise precision within a category. - Devices. Choose
deviceinitially, create directly withdevice=, reassignTensor.toand useModule.toin place. GPU execution is asynchronous:.item(),.cpu(),printandifon tensors synchronize. GPU pays off with enough work per launch and per byte across PCIe; with resident data, product crossover is . - Views.
viewis strict andreshapepermissive, with the same criterion ;expandsets stride 0 and forbids in-place operations;contiguouscopies only if needed andclonepreserves a dense tensor’s strides. - NumPy.
from_numpy,as_tensorwithout conversion and.numpy()share memory and dtype;torch.tensorcopies..numpy()fails on GPU, withrequires_gradand withbfloat16, anddetach().cpu().numpy()shares on CPU. - Translation. Same broadcasting, indexing and einsum rules;
dimandkeepdim,stdwith by default, lowermedian,max(dim)with indices.