Module contents
Lesson 12 of 24Core 60 min

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:

operationCPUGPU
A @ B with n=4096n = 4096162 ms19 ms
A @ B with n=128n = 12811 µs24 µs
torch.exp(x) with 10410^4 elements15 µs22 µs
copy the n=4096n = 4096 matrix (64 MiB) from CPU to GPU5.7 ms
A @ B with n=2048n = 2048 in float64about 430 GFLOP/sabout 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 (i1,…,id)(i_1, \dots, i_d) is at storage position o+∑kiksko + \sum_k i_k s_k, 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.

NumPyPyTorchdifference
buffer, a.baset.untyped_storage(), t._basestorage is an object with its own size and device
a.strides (bytes)t.stride() (elements)multiply by t.element_size()
pointer to first elementt.storage_offset()explicit offset, in elements
negative stridesdo not existtorch.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_contiguoust.is_contiguous()size-1 axes do not count in either
t.device, t.requires_grad, t.grad_fnnew 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.

[ ]Anatomy of a tensor and five derived tensorsLocal GPU
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())
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

dtypebits (sign, exponent, mantissa)maximumε\epsuse
torch.float641, 11, 521.8⋅103081.8 \cdot 10^{308}2.2⋅10−162.2 \cdot 10^{-16}verification, statistics; extremely slow on consumer GPUs
torch.float321, 8, 233.4⋅10383.4 \cdot 10^{38}1.2⋅10−71.2 \cdot 10^{-7}default: parameters, optimizer
torch.bfloat161, 8, 73.4⋅10383.4 \cdot 10^{38}7.8⋅10−37.8 \cdot 10^{-3}mixed-precision activations and weights
torch.float161, 5, 1065504655049.8⋅10−49.8 \cdot 10^{-4}mixed precision with loss scaling
torch.int64 (long)649.2⋅10189.2 \cdot 10^{18}indices, class labels
torch.int32, torch.uint832, 8counts; raw images
torch.bool8masks

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 28=2562^8 = 256, so in bfloat16 256+1=256256 + 1 = 256, and π\pi is stored as 3.1406253.140625. In exchange, it never overflows where float32 does not: a gradient of 10−3010^{-30} or activation of 10610^{6} fits easily, while float16 turns 7000070000 into infinity and rounds below roughly 3⋅10−83 \cdot 10^{-8} 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 numel×element_size\text{numel} \times \text{element\_size}. An activation tensor of shape (B,T,d)=(64,512,768)(B, T, d) = (64, 512, 768) has 64⋅512⋅768≈2.5⋅10764 \cdot 512 \cdot 768 \approx 2.5 \cdot 10^7 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]) is float32 (the default dtype, torch.get_default_dtype()), but np.array([1.0]) is float64.
  • torch.from_numpy and torch.as_tensor preserve the array’s dtype: a float64 array gives a float64 tensor.
  • Integers are int64 in both, and PyTorch requires int64 in many places: cross_entropy rejects int32 labels with expected scalar type Long but found Int.
  • / between integers gives floating point in both, but float32 in PyTorch and float64 in 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.

[ ]Defaults, promotion and 16-bit formatsLocal GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 errors, PCIe copies and synchronizationLocal GPU
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)}")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 kk chained operations on n×nn \times n float32 matrices, either products X = X @ W or an elementwise function such as X = torch.tanh(X). Let PcP_c and PgP_g be sustained CPU and GPU matmul FLOP/s, oco_c CPU overhead per operation, LL GPU kernel launch cost, β\beta PCIe bandwidth, and λ\lambda fixed latency per copy. A product costs W=2n3W = 2n^3 operations and each matrix occupies 4n24n^2 bytes. Then

TCPU=k(oc+2n3Pc),TGPU=Tcopias+k(L+2n3Pg),T_{\text{CPU}} = k\left(o_c + \frac{2n^3}{P_c}\right), \qquad T_{\text{GPU}} = T_{\text{copias}} + k\left(L + \frac{2n^3}{P_g}\right),

where Tcopias=0T_{\text{copias}} = 0 if data are already on GPU (the Spanish label denotes copy time), 2λ+12n2/β2\lambda + 12n^2/\beta if XX and WW are uploaded initially and XX downloaded at the end, and of order k(2λ+8n2/β)k(2\lambda + 8n^2/\beta) if XX goes up and down each step. For elementwise operations, the computation term is memory traffic, 8n28n^2 bytes (read and write), divided by each device’s memory bandwidth.

Proof

With Tcopias=0T_{\text{copias}} = 0, dividing TGPU<TCPUT_{\text{GPU}} < T_{\text{CPU}} by kk gives L+2n3/Pg<oc+2n3/PcL + 2n^3/P_g < o_c + 2n^3/P_c, or 2n3(1/Pc−1/Pg)>L−oc2n^3(1/P_c - 1/P_g) > L - o_c. Both sides are positive by assumption and the left increases in nn, giving threshold n∗n^*. If XX goes up and down each step, add 2λ+8n2/β2\lambda + 8n^2/\beta per step to the GPU side; for large nn the highest-order terms dominate, 2n3(1/Pc−1/Pg)>8n2/β2n^3(1/P_c - 1/P_g) > 8n^2/\beta, giving n>4/(β(1/Pc−1/Pg))n > 4/(\beta(1/P_c - 1/P_g)). For elementwise operations with a copy each step, the GPU pays at least for 8n28n^2 PCIe bytes and a launch, 8n2/β+L8n^2/\beta + L, while the CPU pays 8n2/Bc+oc8n^2/B_c + o_c. If β<Bc\beta < B_c, each GPU term exceeds its CPU counterpart (the second by L>ocL > o_c): the copy and launch alone are slower than the entire CPU step.

∎

With lab measurements Pc=900P_c = 900 GFLOP/s, Pg=7P_g = 7 TFLOP/s, oc=3o_c = 3 µs and L=12L = 12 µs, we get n∗≈167n^* \approx 167, consistent with the opening table (CPU wins at n=128n = 128 and loses at n=256n = 256). With copies every step and β=11\beta = 11 GB/s, the crossover rises to several hundred. Behind the proposition is arithmetic intensity: a product performs 2n32n^3 operations on 12n212n^2 bytes, n/6n/6 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.

InteractiveDoes the GPU pay off?
X = X @ W once · upload X (and W) initially, k GPU steps, download X at the end
1 µs100 µs10 ms1 s1632641282565121024204840968192n (log scale)crossover n* ≈ 617GPU wins
  • CPU
  • GPU, total
  • GPU without copies
Breakdown at n = 256 (linear scale)CPU40.3 µsGPU118 µs
  • PCIe copies (101 µs)
  • launches (12.0 µs)
  • GPU compute (4.79 µs)
Work
Operation
256 (256 KiB)
1
Data
PCIe copies
CPU time40.3 µs
GPU time118 µs
GPU speedup×0.34 (slower)
GPU time spent on PCIe86 %
crossover n∗n^*≈ 617
At n=256n = 256 GPU loses: over half its time is spent on PCIe copies. Increase nn or chain more operations.
Total time for kk operations on n×nn \times n 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 n=256n = 256 matmul copied round-trip: GPU loses. Raise kk to 100 and watch the crossover approach the resident-data case. Then switch to tanh with copies each step: is there any nn 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 k=1k = 1 and round-trip copies, the matmul crossover is around n≈600n \approx 600, and below that most GPU time is copying. The dashed GPU-without-copies curve shows the bus cost.
  • Chaining operations amortizes copies. With k=100k = 100, two copies are spread across a hundred products and crossover falls to n≈170n \approx 170, nearly the proposition’s n∗n^*. Models are therefore uploaded once and data stay on GPU throughout the training step.
  • Copying each step is fatal for low-compute work. With tanh and 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 n=32n = 32, 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.bmm instead 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 n=512n = 512 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.

[ ]Cost-model crossover pointsBrowser
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 sk=nk+1sk+1s_k = n_{k+1} s_{k+1}. 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 (1,n)(1, n), and merging them would require 1=mn1 = m n. reshape does not fail: it calls view if possible and contiguous().view(...) otherwise, implicitly copying.

InteractiveStorage inspector
0120123048159261037110011223344556677889910101111storage of x: 12 × float32 = 48 B
  • row 0 of x
  • row 1
  • row 2
  • ×k: logical elements sharing this position
  • storage_offset
y[0,2]→0+0⋅1+2⋅4=8\texttt{y}[0, 2] \to 0 + 0\cdot 1 + 2\cdot 4 = 8
The same position is also read by: x[2, 0].
Where x lives
Device
Operations on y
Write in place
y.shapetorch.Size([4, 3])
y.stride()(1, 4)
storage_offset()0
is_contiguous()False
Shares memory with x?yes
y._version0
y = x.t() is a view: the same 12-element storage read with strides (1,4)(1, 4), no longer in C order. Try view(12) on y, then reshape(12).
A family of tensors built from 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 ×k\times k 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:

  • view fails where reshape copies, for the same reason. On y = x.t(), with strides (1,4)(1, 4), view(12) raises RuntimeError and reshape(12) creates new storage (a different-colored card). In contrast view(2, 2, 3) works: it only splits the size-4 axis.
  • expand copies nothing. x[0].expand(2, 4) has strides (0,1)(0, 1) and the ×2\times 2 badges show each storage position appears twice. An add_ on it fails with more 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) on x[..., 1:] also changes x, y and every view reading those positions (magenta-bordered cards), and the _version counter shared by the family increases. A copy remains unaffected.
  • clone preserves layout, contiguous does not. The clone of x.t() has its own data but the same strides (1,4)(1, 4): 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 += 100 on 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 δ\boldsymbol{\delta} with ∣δk∣<nk\abs{\delta_k} < n_k and ∑kδksk=0\sum_k \delta_k s_k = 0, 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.

ProofProving the nonoverlap condition
Prove: If sorted positive strides satisfy sk+1≥nksks_{k+1} \ge n_k s_k, distinct indices never have the same address.
0
Suppose i≠i′\vb{i} \ne \vb{i}' with ∑kiksk=∑kik′sk\sum_k i_k s_k = \sum_k i'_k s_k and let δk=ik−ik′\delta_k = i_k - i'_k, so ∣δk∣≤nk−1\abs{\delta_k} \le n_k - 1 and ∑kδksk=0\sum_k \delta_k s_k = 0.

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.

[ ]View metadata without data: transpose, expand and viewLocal GPU
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())
This cell needs the local lab (PyTorch with your GPU). Start it with 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 (2,3)(2, 3) and strides (12,4)(12, 4), remain in relative C order (12=3⋅412 = 3 \cdot 4). What matters is whether the axes being merged were reordered relative to each other. The second merges axes with strides (1,4)(1, 4) and fails. Now compare with PyTorch over thousands of random operation chains.

[ ]Testing against PyTorch: 3000 random chainsLocal GPU
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}")
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

conversioncopy?dtypenotes
torch.from_numpy(a)nevera’sfails with negative strides; warns if a is read-only
torch.as_tensor(a)only if neededa’s or requestedcopies if dtype changes or another device is requested
torch.tensor(a)alwaysa’ssafe way to make an independent copy
t.numpy()nevert’sTypeError on GPU, RuntimeError with requires_grad, TypeError with bfloat16
t.detach().cpu().numpy()only if t is on GPUt’son CPU, .cpu() returns the same tensor and shares
t.numpy(force=True)if neededt’sequivalent to detach().cpu()...numpy()
torch.from_dlpack(x), np.from_dlpack(t)neverDLPack 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.

[ ]Shared memory without surprisesLocal GPU
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], "...")
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

NumPyPyTorchbeware
axis=, keepdims=Truedim=, 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.stacktorch.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 n−1n - 1 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.attorch.gather, index_add_ / scatter_add_int64 indices
np.argpartition + take_along_axistorch.topkreturns sorted values and indices
np.einsumtorch.einsumsame notation, from the einsum lesson
np.random.default_rng(0)torch.Generator().manual_seed(0)per-device generators
np.allclosetorch.testing.assert_closedefault tolerances depend on dtype

The standard deviation row causes the most silently wrong results: for [1,2,3,4][1, 2, 3, 4], NumPy gives 1.1181.118 and PyTorch 1.2911.291. 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.

[ ]The module library, ported and verifiedLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Distances need explicit tolerances because the identity ∥x∥2+∥y∥2−2x⊤y\norm{\vb{x}}^2 + \norm{\vb{y}}^2 - 2\vb{x}\T\vb{y} 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.

[ ]CPU versus GPU, with and without copies, and your hardware parametersLocal GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 O(N2)\bigO(N^2) computation on O(N)\bigO(N) data the bus matters little, because arithmetic intensity grows with NN. 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

QuizChains of views
Let x = torch.arange(24.).reshape(2, 3, 4), with strides (12,4,1)(12, 4, 1). Which statements are true? More than one may apply.

More than one answer may be correct.

CodeMove a nested batch
Implement 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 batch
Shift+Enter to run
NumericActivation memory
How many MiB (2202^{20} bytes) does a bfloat16 tensor of shape (64,512,768)(64, 512, 768) occupy?
QuizThree dtypes and a training run
What dtypes do 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?
QuizSynchronization points
Inside a training loop with everything on GPU, which lines force the CPU to wait for queued GPU work to finish? More than one may apply.

More than one answer may be correct.

NumericThe crossover point
Using the lesson's cost model, Pc=900P_c = 900 GFLOP/s, Pg=7P_g = 7 TFLOP/s, oc=3o_c = 3 µs, L=12L = 12 µs and data already on GPU, above what size nn is an n×nn \times n matrix product faster on GPU? Give the real value of n∗n^*.
NumericConvert before or after copying
A uint8 image batch of shape (256,3,224,224)(256, 3, 224, 224) goes to GPU over PCIe at 12 GB/s (12⋅10912 \cdot 10^9 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

Key idea
A PyTorch tensor is an ndarray with a device, deep-learning dtypes and autograd history: storage plus shape, element strides and offset. All this lesson’s rules follow from that structure. An operation is a view if new strides exist over the same storage, an in-place operation reaches everything sharing storage, and moving data between devices copies over a bus that pays off only when each transferred byte feeds substantial computation.
  • Anatomy. Shareable storage, dtype, device, shape, strides in elements, storage_offset and autograd state. No negative strides. Views share storage and version counter.
  • dtypes. float32 by default, int64 for indices, bfloat16 (float32 range, 8 bits of precision) and float16 (small range) for mixed precision, float64 rarely on consumer GPUs. Promotion considers whether operands have axes: a scalar or zero-axis tensor does not raise precision within a category.
  • Devices. Choose device initially, create directly with device=, reassign Tensor.to and use Module.to in place. GPU execution is asynchronous: .item(), .cpu(), print and if on tensors synchronize. GPU pays off with enough work per launch and per byte across PCIe; with resident data, product crossover is n∗=((L−oc)/(2(1/Pc−1/Pg)))1/3n^* = \big((L - o_c)/(2(1/P_c - 1/P_g))\big)^{1/3}.
  • Views. view is strict and reshape permissive, with the same criterion sk=nk+1sk+1s_k = n_{k+1}s_{k+1}; expand sets stride 0 and forbids in-place operations; contiguous copies only if needed and clone preserves a dense tensor’s strides.
  • NumPy. from_numpy, as_tensor without conversion and .numpy() share memory and dtype; torch.tensor copies. .numpy() fails on GPU, with requires_grad and with bfloat16, and detach().cpu().numpy() shares on CPU.
  • Translation. Same broadcasting, indexing and einsum rules; dim and keepdim, std with n−1n - 1 by default, lower median, max(dim) with indices.