Python for AI Engineers · Part C · Lesson 23 of 26

PyTorch basics: tensors, autograd and GPUs for AI engineers

PyTorch for Java and JavaScript developers: install it with uv, create tensors and read their shape, dtype and device, move data to and from NumPy, broadcast and multiply matrices, reshape and index, let autograd compute gradients, and run on cuda or Apple mps.

⏱ 45 min3 exercises that check your codeRuns in your browser

By the end you can

  • Install PyTorch with uv (including the small CPU-only build on Linux) and check which devices you have
  • Create tensors and read their shape, dtype and device, and move data between NumPy and PyTorch safely
  • Use broadcasting, @, view/reshape, indexing and topk the way model and retrieval code does
  • Explain what a gradient is, and let autograd compute it with requires_grad, backward(), .grad and torch.no_grad()
  • Pick cuda, mps or cpu at run time and keep every tensor on the same device
1 / 6

1What PyTorch is, and installing it

PyTorch is the library most neural networks are written in, including most open models you will run or fine-tune. Its core type is the tensor: an n-dimensional array of numbers, just like a NumPy array from the NumPy lesson. It adds two things NumPy does not have: it can run on a GPU, and it can work out gradients for you (autograd), which is what training needs.

PyTorch is a large compiled library, so it cannot run in these browser boxes. In this lesson the PyTorch examples are files you run on your machine; each one shows the exact output it printed. The parts NumPy or plain Python can show run right here in the page.

Create a project and add PyTorch and NumPy (pinned, so your output matches this page). uv init makes a folder with a pyproject.toml, and uv add installs the packages into the project's .venv and records them. On a Mac or Windows this is all you need:

Run
uv init tensors-demo --python 3.12
cd tensors-demo
uv add torch==2.15.0 numpy==2.5.5
You should see
 + numpy==2.5.5
 + torch==2.15.0
 (plus about 9 helper packages such as sympy, networkx and jinja2)
check.py
import torch

print(torch.__version__)
print("cuda:", torch.cuda.is_available())
print("mps:", torch.backends.mps.is_available())
print(torch.ones(2, 3) * 2)
  1. The installed version. On Linux it ends with a build tag: +cpu for the CPU-only build, or a CUDA tag such as +cu132 for the default build.line 3
  2. True only with an NVIDIA GPU and its driver. CUDA is NVIDIA's GPU platform.line 4
  3. True on a Mac with Apple silicon (M1 or newer). MPS (Metal Performance Shaders) is Apple's GPU backend.line 5
  4. A first tensor: a 2 by 3 grid of ones, times 2.line 6
Output
2.15.0
cuda: False
mps: True
tensor([[2., 2., 2.],
        [2., 2., 2.]])

Run it with uv run python check.py (uv run runs a command inside the project's environment). The output above is from an Apple silicon Mac. On a Linux or Windows machine without an NVIDIA GPU both lines say False, and that is fine: everything in this lesson runs on the CPU.

On Linux, add the CPU-only index first. On Linux, plain uv add torch installs the CUDA build, which pulls in several gigabytes of NVIDIA libraries even on a laptop with no NVIDIA GPU. If you do not have one, tell uv to fetch torch from PyTorch's own CPU-only index by adding this to pyproject.toml before the uv add line:

[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true

[tool.uv.sources]
torch = [{ index = "pytorch-cpu", marker = "sys_platform == 'linux'" }]

[[tool.uv.index]] registers an extra package index (a server uv downloads packages from, like a Maven repository). explicit = true means uv uses it only for packages that point to it. [tool.uv.sources] points torch there, and the marker limits that to Linux, so a teammate on a Mac still gets the normal build from PyPI. Then run the same uv add line. The CPU build is a download of a few hundred megabytes instead of several gigabytes.

Tip Pin the torch version in every project. Models saved with one version usually load in newer ones, but numbers, warnings and defaults do shift between releases, and a pinned version makes "works on my machine" true for everyone.

2Tensors: shape, dtype and device

Every tensor has three properties you will check all the time. shape: how many numbers along each dimension (a torch.Size, which behaves like a tuple). dtype: the number type of every element. device: where the numbers live, cpu or a GPU.

torch.tensor(...) builds a tensor from Python lists. PyTorch also has the same factory functions as NumPy: zeros, ones, arange, full, and random ones. The one difference that bites: a list of Python floats becomes float32 in PyTorch, while NumPy makes float64. Neural networks use float32 (or smaller) because it is half the memory and much faster on GPUs.

tensors.py
import torch

x = torch.tensor([[1.0, 2.0, 3.0],
                  [4.0, 5.0, 6.0]])
print(x)
print(x.shape, x.dtype, x.device)
print(x.ndim, x.numel())

ids = torch.tensor([101, 7592, 102])     # whole numbers, like token ids
print(ids.dtype)

print(torch.zeros(2, 3))
print(torch.ones(3, dtype=torch.int64))
print(torch.arange(0, 10, 3))
print(torch.full((2, 2), 0.5))

torch.manual_seed(0)                     # same random numbers on every run
print(torch.rand(2, 3))                  # uniform between 0 and 1
print(torch.randn(3))                    # normal: mean 0, standard deviation 1
  1. A nested list becomes a 2D tensor: 2 rows of 3 numbers.line 3
  2. torch.Size([2, 3]), torch.float32 and cpu. Tensors start on the CPU unless you say otherwise.line 6
  3. ndim is the number of dimensions (2), numel() the number of elements (2 x 3 = 6).line 7
  4. Python ints become int64 (a Java long). Token ids and class labels are stored like this.line 9
  5. Any factory takes dtype= to choose the type yourself.line 13
  6. Like Python's range: from 0, below 10, in steps of 3.line 14
  7. Seeds the random generator, like new Random(0) in Java. Weights in a new model start random, so seeding makes runs repeatable.line 17
Output
tensor([[1., 2., 3.],
        [4., 5., 6.]])
torch.Size([2, 3]) torch.float32 cpu
2 6
torch.int64
tensor([[0., 0., 0.],
        [0., 0., 0.]])
tensor([1, 1, 1])
tensor([0, 3, 6, 9])
tensor([[0.5000, 0.5000],
        [0.5000, 0.5000]])
tensor([[0.4963, 0.7682, 0.0885],
        [0.1320, 0.3074, 0.6341]])
tensor([ 1.2645, -0.6874,  0.1604])

PyTorch prints floats with a trailing dot (1.) and pads them to line up, and shows four decimals when they are not whole numbers. A tensor with a dtype other than the default float32 or int64 shows it in the printout, as you will see in the next section.

Watch out Mixing dtypes is the most common first error. A model's weights are float32; feed it a float64 tensor and you get RuntimeError: mat1 and mat2 must have the same dtype, but got Double and Float (Double is float64, Float is float32). Convert with .float() before the data reaches the model.

3NumPy in, NumPy out

Data often arrives as NumPy arrays: from pandas, from an embedding library, from a file. There are two ways in, and they behave differently. torch.from_numpy(a) shares memory with the array: no copy, so it is instant, but changing one changes the other. torch.tensor(a) makes a copy.

The way out is t.numpy(), which also shares memory. It only works for a tensor on the CPU that is not tracking gradients; you will meet requires_grad properly in section 8.

interop.py
import numpy as np
import torch

a = np.array([1.0, 2.0, 3.0])          # NumPy defaults to float64
shared = torch.from_numpy(a)           # no copy: same memory as a
copied = torch.tensor(a)               # a new copy
print(shared.dtype, copied.dtype)

a[0] = 100.0                           # change the NumPy array
print(shared)
print(copied)

small = torch.from_numpy(a).float()    # float32 copy, the usual choice for models
print(small)

back = small.numpy()                   # tensor -> NumPy, again sharing memory
print(type(back).__name__, back.dtype)

w = torch.ones(2, requires_grad=True)
try:
    w.numpy()
except RuntimeError as e:
    print("error:", e)
print(w.detach().numpy())
  1. Shares the array's memory and keeps its dtype, float64.line 5
  2. Changing the NumPy array shows up in shared (it is the same memory) but not in copied.line 9
  3. .float() converts to float32. A dtype change always makes a new copy, so small no longer shares memory with a.line 13
  4. Back to NumPy without a copy. The array is float32 because small is.line 16
  5. A tensor that tracks gradients refuses, because NumPy cannot track them. .detach() gives a version without tracking.line 21
Output
torch.float64 torch.float64
tensor([100.,   2.,   3.], dtype=torch.float64)
tensor([1., 2., 3.], dtype=torch.float64)
tensor([100.,   2.,   3.])
ndarray float32
error: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
[1. 1.]

Tip For model input, use torch.from_numpy(arr).float(): no copy on the way in, and the float32 the model expects. For output, t.detach().cpu().numpy() works from any device and any tensor.

4Broadcasting and matrix multiply (runs here with NumPy)

PyTorch follows the same broadcasting rules as NumPy, so you can practise them right here. When two arrays of different shapes meet in +, * or /, the shapes are lined up from the right. Each pair of sizes must be equal, or one of them must be 1 (or missing), and that one is stretched to match without copying data.

@ is matrix multiply. (3, 4) @ (4,) gives (3,): one dot product per row. That is exactly how a search scores every document embedding against a query in one line. Run it, then change a shape to see the error.

Try it: edit and run
import numpy as np

docs = np.array([[1.0, 0.0, 1.0, 0.0],     # 3 documents, 4 numbers each: shape (3, 4)
                 [0.0, 2.0, 0.0, 2.0],
                 [1.0, 1.0, 1.0, 1.0]])
query = np.array([1.0, 0.0, 1.0, 0.0])     # one query: shape (4,)

print("docs  ", docs.shape)
print("scores", docs @ query)              # (3, 4) @ (4,) -> (3,): one score per document

print(docs * 10)                           # a scalar is stretched to every element
print(docs + np.array([0.5, 0.5, 0.0, 0.0]))   # (3, 4) + (4,): the row is added to each row

lengths = np.sqrt((docs ** 2).sum(axis=1))     # (3,): one length per document
print("lengths", lengths)
unit = docs / lengths[:, None]                 # (3, 4) / (3, 1): each row divided by its own length
print(unit.round(3))

try:
    docs + np.array([1.0, 2.0, 3.0])           # (3, 4) + (3,): 4 and 3 do not match
except ValueError as e:
    print("error:", e)
Expected output
docs   (3, 4)
scores [2. 0. 2.]
[[10.  0. 10.  0.]
 [ 0. 20.  0. 20.]
 [10. 10. 10. 10.]]
[[1.5 0.5 1.  0. ]
 [0.5 2.5 0.  2. ]
 [1.5 1.5 1.  1. ]]
lengths [1.41421356 2.82842712 2.        ]
[[0.707 0.    0.707 0.   ]
 [0.    0.707 0.    0.707]
 [0.5   0.5   0.5   0.5  ]]
error: operands could not be broadcast together with shapes (3,4) (3,)

lengths[:, None] adds a dimension of size 1, turning shape (3,) into (3, 1), so each row is divided by its own length. Without it, (3, 4) / (3,) fails exactly like the last line. Dividing every vector by its length is the normalising step of cosine similarity.

The same code in PyTorch, with the shapes you will meet in real models: a layer turning 768 numbers into 10, and attention scores between tokens (a (4, 8, 64) tensor is 4 sentences, 8 tokens each, 64 numbers per token). @ on 3D tensors multiplies the last two dimensions and treats the first as a batch.

import torch

batch = torch.randn(32, 768)          # 32 inputs, 768 numbers each
weights = torch.randn(768, 10)        # a layer that turns 768 numbers into 10
bias = torch.zeros(10)
out = batch @ weights + bias          # (32, 768) @ (768, 10) -> (32, 10), then + (10,)
print(out.shape)

q = torch.randn(4, 8, 64)             # 4 sentences, 8 tokens each, 64 numbers per token
k = torch.randn(4, 8, 64)
scores = q @ k.transpose(-2, -1)      # swap the last two dims: (4, 8, 64) @ (4, 64, 8) -> (4, 8, 8)
print(scores.shape)

try:
    batch @ torch.randn(10, 768)      # inner sizes 768 and 10 do not match
except RuntimeError as e:
    print("error:", e)
torch.Size([32, 10])
torch.Size([4, 8, 8])
error: mm: mat1 and mat2 shapes cannot be multiplied (32x768 and 10x768)

The error message names the two shapes. Read it as "the inner sizes must match": (a, n) @ (n, b) gives (a, b). transpose(-2, -1) swaps the last two dimensions; negative numbers count from the end, as in Python lists.

Watch out Broadcasting never complains when the shapes happen to fit, even if you meant something else. (3, 1) + (3,) silently gives a (3, 3) grid, not 3 numbers. Print .shape after every step while you are writing tensor code.

5Reshaping: view, reshape, unsqueeze

Model code reshapes constantly: flatten an image into one row of numbers, add a batch dimension of 1 before calling a model, split 768 numbers into 12 attention heads of 64. The numbers stay the same; only how you index them changes.

view(...) gives a new shape over the same memory, so it is instant, and -1 means "work out this size from the others". unsqueeze(i) inserts a dimension of size 1 at position i, squeeze() removes them. permute reorders dimensions.

shapes.py
import torch

x = torch.arange(12.0)                # 0., 1., ..., 11.: shape (12,)
m = x.view(3, 4)                      # same 12 numbers seen as 3 rows of 4
print(m)
print(x.view(2, -1).shape)            # -1: "work this one out for me" -> (2, 6)

m[0, 0] = 99.0                        # view shares memory with x
print(x[:3])

v = torch.tensor([1.0, 2.0, 3.0])     # shape (3,)
print(v.unsqueeze(0).shape)           # (1, 3): a batch of one
print(v.unsqueeze(1).shape)           # (3, 1): a column
print(torch.zeros(1, 3, 1).squeeze().shape)   # drops every size-1 dimension -> (3,)

t = m.T                               # transpose (4, 3): no copy, just new strides
print(t.is_contiguous())
try:
    t.view(12)
except RuntimeError as e:
    print("error:", e)
print(t.reshape(12)[:4])              # reshape copies when it has to
print(t.contiguous().view(12)[:4])

images = torch.zeros(8, 28, 28)       # 8 images of 28 x 28 pixels
print(images.flatten(start_dim=1).shape)   # keep the batch, flatten the rest -> (8, 784)
print(images.permute(1, 2, 0).shape)  # reorder dimensions -> (28, 28, 8)
  1. arange(12.0) with a float gives float32 numbers 0 to 11.line 3
  2. 12 numbers in 2 rows: the -1 becomes 6. Only one size can be -1, and the total must still be 12.line 6
  3. Writing through the view changes x too: they share memory, like two Java references to one array.line 8
  4. The usual way to call a model with one example: models expect a batch, so (3,) becomes (1, 3).line 12
  5. .T transposes a 2D tensor without copying, by changing the strides (how far to jump in memory for each index). The result is not **contiguous**: its rows are not laid out one after another in memory.line 16
  6. view needs memory that fits the new shape, so it fails here.line 19
  7. reshape is a view when it can be, and a copy when it must. .contiguous() makes the copy explicitly.line 22
  8. flatten(start_dim=1) keeps dimension 0 (the batch) and joins the rest: 28 x 28 = 784.line 26
Output
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.]])
torch.Size([2, 6])
tensor([99.,  1.,  2.])
torch.Size([1, 3])
torch.Size([3, 1])
torch.Size([3])
False
error: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.
tensor([99.,  4.,  8.,  1.])
tensor([99.,  4.,  8.,  1.])
torch.Size([8, 784])
torch.Size([28, 28, 8])

Tip Use reshape by default; reach for view when you want an error if a copy would be needed. NumPy has the same idea: arr.reshape(...) and arr[None, :] for a new dimension.

6Indexing, masks and top-k

Indexing works like NumPy: t[0] is the first row, t[:, 1] is column 1 of every row, t[i, j] is one element, and a boolean tensor picks out the elements where it is True. One difference from NumPy: a single element is still a 0-dimensional tensor. .item() turns it into a plain Python number, and .tolist() turns a whole tensor into Python lists.

argmax(dim=1) gives the position of the biggest value in each row: that is how a classifier picks its class. topk(k) gives the k biggest values and their positions: that is the "find the 2 most similar chunks" step of RAG.

indexing.py
import torch

scores = torch.tensor([[0.1, 0.7, 0.2],      # 2 inputs, 3 classes each
                       [0.8, 0.1, 0.1]])
print(scores[0])                  # first row
print(scores[:, 1])               # column 1 of every row
print(scores[1, 0])               # one element: still a tensor
print(scores[1, 0].item())        # .item() turns a one-element tensor into a Python number

print(scores.argmax(dim=1))       # best class per row
print(scores > 0.5)               # a boolean tensor of the same shape
print(scores[scores > 0.5])       # only the elements where the mask is True

sims = torch.tensor([0.12, 0.91, 0.45, 0.78, 0.33])   # similarity of 5 chunks to a query
top = sims.topk(2)
print(top.values, top.indices)
chunks = ["intro", "pricing", "faq", "refunds", "contact"]
print([chunks[i] for i in top.indices.tolist()])

x = torch.zeros(3)
x[1] = 5.0                        # assignment works like an array
x += 1                            # in place: changes x itself
print(x, x.sum().item(), x.mean().item())
  1. Prints tensor(0.8000): a tensor with zero dimensions, shape torch.Size([]).line 7
  2. The Python number shows the float32 rounding: 0.8 cannot be stored exactly in 32 bits. Python floats are 64-bit, so the tiny error becomes visible.line 8
  3. dim=1 means "along each row" (across the columns). dim=0 would give the best row for each column.line 10
  4. topk returns a pair with .values and .indices, sorted from the largest down.line 15
  5. .tolist() turns the index tensor into Python ints, so they can index a normal list.line 18
  6. Operators like += and methods ending in _ (such as zero_()) change the tensor in place.line 22
Output
tensor([0.1000, 0.7000, 0.2000])
tensor([0.7000, 0.1000])
tensor(0.8000)
0.800000011920929
tensor([1, 0])
tensor([[False,  True, False],
        [ True, False, False]])
tensor([0.7000, 0.8000])
tensor([0.9100, 0.7800]) tensor([1, 3])
['pricing', 'refunds']
tensor([1., 6., 1.]) 8.0 2.6666667461395264

Watch out Calling .item() or .tolist() inside a hot loop on a GPU tensor forces the program to wait for the GPU and copy each value back. Do the maths on whole tensors and convert once at the end.

7What a gradient is (runs here in plain Python)

Training a model means: measure how wrong it is (the loss), then nudge every weight in the direction that makes the loss smaller, and repeat. The gradient says which direction that is. For one weight it is just the slope: if increasing w a little makes the loss go up, the slope is positive, so you decrease w.

You can estimate a slope with no maths at all: change w a tiny bit up and down and see how much the loss changes. The tiny model below predicts y = w * x for one example where x = 2 and the right answer is 10, so the best w is 5. Run it and watch w walk towards 5.

Try it: edit and run
def loss(w):
    """How wrong the tiny model y = w * x is on one example: x = 2, the right answer is 10."""
    prediction = w * 2.0
    return (prediction - 10.0) ** 2


def slope(f, w, h=1e-4):
    """Nudge w a tiny bit both ways and measure how much f changes per unit of w."""
    return (f(w + h) - f(w - h)) / (2 * h)


w = 3.0
print("slope at w = 3:", round(slope(loss, w), 4))

for step in range(1, 4):
    current = loss(w)
    w = w - 0.1 * slope(loss, w)        # a small step against the slope: downhill
    print(f"step {step}: loss {current:.4f}, new w = {w:.4f}")
Expected output
slope at w = 3: -16.0
step 1: loss 16.0000, new w = 4.6000
step 2: loss 0.6400, new w = 4.9200
step 3: loss 0.0256, new w = 4.9840

0.1 is the learning rate: how big a step to take. Too big and w jumps past 5 and bounces around; too small and training takes forever. This nudging method works for one weight, but a real model has millions or billions of weights, and nudging each one separately would take millions of loss evaluations per step. Autograd gets all the slopes from a single backward pass, and it gets them exactly.

8Autograd: requires_grad, backward and no_grad

Mark a tensor with requires_grad=True and PyTorch records every operation that uses it, building a graph of how the result was computed. Calling .backward() on a single number (the loss) walks that graph in reverse and stores the slope of the loss with respect to each marked tensor in its .grad. This is the same model and the same steps as the box above, now with exact gradients.

autograd.py
import torch

w = torch.tensor(3.0, requires_grad=True)   # track every operation that uses w
x = torch.tensor(2.0)
target = torch.tensor(10.0)

loss = (w * x - target) ** 2
print(loss)
loss.backward()                             # compute d(loss)/d(w) and store it in w.grad
print(w.grad)

loss = (w * x - target) ** 2
loss.backward()                             # a second backward ADDS to w.grad
print(w.grad)
w.grad.zero_()                              # so reset it before every step

for step in range(1, 4):
    loss = (w * x - target) ** 2
    loss.backward()
    with torch.no_grad():                   # the update itself must not be tracked
        w -= 0.1 * w.grad
    w.grad.zero_()
    print(f"step {step}: loss {loss.item():.4f}, new w = {w.item():.4f}")
  1. A weight we want gradients for. Only floating-point tensors can require gradients.line 3
  2. The printout shows grad_fn: the loss remembers which operation made it, so backward can retrace the steps.line 8
  3. Fills w.grad with d(loss)/d(w). By the chain rule that is 2 x (2w - 10) x 2 = -16 at w = 3, the same slope as the box above.line 9
  4. Gradients **add up** across backward calls (handy for advanced tricks, a bug otherwise). That is why it now shows -32.line 13
  5. Resets the gradient to 0 in place. Training loops do this every step (optimizer.zero_grad() in the next lesson).line 15
  6. Inside torch.no_grad() nothing is recorded. Changing w in place outside it raises "a leaf Variable that requires grad is being used in an in-place operation".line 20
Output
tensor(16., grad_fn=<PowBackward0>)
tensor(-16.)
tensor(-32.)
step 1: loss 16.0000, new w = 4.6000
step 2: loss 0.6400, new w = 4.9200
step 3: loss 0.0256, new w = 4.9840

The same works for a whole vector of weights: the gradient has the same shape as the weights, one slope per weight. Here a model with two weights, scored with the mean squared error over three examples:

import torch

X = torch.tensor([[1.0, 2.0],
                  [3.0, 4.0],
                  [5.0, 6.0]])                 # 3 examples, 2 features each
y = torch.tensor([5.0, 11.0, 17.0])           # the right answers
w = torch.zeros(2, requires_grad=True)        # 2 weights, start at 0

loss = ((X @ w - y) ** 2).mean()             # mean squared error over the 3 examples
loss.backward()
print(loss.item(), w.grad, w.grad.shape)

with torch.no_grad():
    preds = X @ w
print(preds.requires_grad, (X @ w).requires_grad)
print(w.detach().requires_grad)
145.0 tensor([ -82., -104.]) torch.Size([2])
False True
False

Use torch.no_grad() whenever you only use a model (inference): answering a request, embedding documents, evaluating. It skips recording the graph, which saves memory and time. .detach() does the same for one tensor: it returns the same numbers without the history. The next lesson, your first neural network, wraps all of this into a training loop with an optimizer.

Tip The pattern every training loop repeats: forward (compute the loss), backward(), update the weights under no_grad, zero the gradients. You will write it many times; once you see these four steps, every training script reads the same.

9Devices: cpu, cuda and mps

A tensor lives on one device. cpu is your normal memory. cuda is an NVIDIA GPU (cuda:0, cuda:1 when there are several). mps is the GPU in Apple silicon Macs. A GPU runs the same maths on thousands of numbers at once, which is why models train and run much faster there.

t.to(device) returns a copy on that device; the original stays where it was, so always keep the result. Every tensor in one operation must be on the same device, otherwise PyTorch raises an error that starts with "Expected all tensors to be on the same device". The usual approach: pick the device once at startup, then move the model and every batch to it.

This file puts it together: it picks the best device, moves made-up document and query embeddings there, and finds the 2 closest chunks with cosine similarity, the search step of RAG.

search.py
import numpy as np
import torch
import torch.nn.functional as F

CHUNKS = ["How to reset your password", "Refund policy", "Pricing plans",
          "Cancel a subscription", "Contact support"]

# In a real app an embedding model makes these. Here: 5 made-up vectors of 4 numbers.
DOC_VECTORS = np.array([[0.9, 0.1, 0.0, 0.1],
                        [0.1, 0.8, 0.3, 0.0],
                        [0.0, 0.3, 0.9, 0.1],
                        [0.2, 0.7, 0.1, 0.4],
                        [0.3, 0.1, 0.1, 0.9]], dtype=np.float32)
QUERY = np.array([0.1, 0.9, 0.2, 0.2], dtype=np.float32)   # "can I get my money back?"


def pick_device() -> torch.device:
    """The fastest device here: an NVIDIA GPU, then Apple silicon, then the CPU."""
    if torch.cuda.is_available():
        return torch.device("cuda")
    if torch.backends.mps.is_available():
        return torch.device("mps")
    return torch.device("cpu")


def search(query: np.ndarray, docs: np.ndarray, k: int, device: torch.device) -> list[tuple[str, float]]:
    with torch.no_grad():                                   # searching, not training
        d = torch.from_numpy(docs).to(device)               # (5, 4), now on the device
        q = torch.from_numpy(query).to(device)              # (4,)
        sims = F.normalize(d, dim=1) @ F.normalize(q, dim=0)   # (5,): cosine similarities
        top = sims.topk(k)
        scores = top.values.cpu().tolist()                  # back to the CPU, then plain Python
        return [(CHUNKS[i], s) for i, s in zip(top.indices.cpu().tolist(), scores)]


def main() -> None:
    device = pick_device()
    print("using", device)
    for chunk, score in search(QUERY, DOC_VECTORS, k=2, device=device):
        print(f"{score:.3f}  {chunk}")


if __name__ == "__main__":
    main()
  1. Checked in order of speed. The same code then runs on a laptop, a Mac and a GPU server.line 17
  2. Searching does not train anything, so no gradients are needed.line 27
  3. from_numpy (no copy), then .to(device) (a copy on the GPU, or the same tensor if the device is already cpu).line 28
  4. F.normalize divides each vector by its length (section 4 did this by hand), so @ gives cosine similarities.line 30
  5. Results go back to the CPU before becoming Python values, the same rule as .numpy().line 32
  6. True only when you run this file directly, not when another file imports it: the same idea as public static void main in Java.line 43
Output
using cpu
0.968  Refund policy
0.945  Cancel a subscription

Run it with uv run python search.py. This output is from a machine with no GPU; on an Apple silicon Mac the first line says using mps and on an NVIDIA machine using cuda, with the same results. Two rules of thumb: create tensors directly on the device when you can (torch.randn(1000, 1000, device=device)), and on mps stick to float32, because Apple's GPU backend does not support float64. A model is moved the same way, model.to(device); for a model (unlike a tensor) this moves it in place and also returns it.

Watch out Writing x.to(device) on its own line does nothing useful: it returns a moved copy that you throw away, and x stays on the CPU. Write x = x.to(device).

Common mistakes

  • Feeding float64 data (straight from NumPy or pandas) to a float32 model and getting "must have the same dtype, but got Double and Float". Call .float() first.
  • Writing x.to(device) without assigning the result, then hitting "Expected all tensors to be on the same device".
  • Forgetting to zero the gradients, so each step adds to the last one and training goes wrong without any error.
  • Running inference without torch.no_grad(), which records a graph nobody needs and wastes memory.
  • Calling .numpy() on a GPU tensor or one that requires grad. Use t.detach().cpu().numpy().
  • Trusting broadcasting blindly: shapes that happen to fit give a wrong result with no error. Print .shape as you go.

Practice

Write the code, then press Check. Your work is saved in this browser.

1Work out a broadcast shape

Write broadcast_shape(a, b) that takes two shapes (tuples of ints) and returns the shape of x + y under the broadcasting rules, or raises ValueError when they do not fit. Line the shapes up from the right; each pair of sizes must be equal or one of them must be 1; a missing size counts as 1.

Exercise
def broadcast_shape(a, b):
    # line the sizes up from the right
    return a
Hint

Loop `i` from 1 to the longer length and compare `a[-i]` and `b[-i]` (use 1 when a shape is too short). Collect the bigger size, then reverse the list at the end.

2Fill in the -1

Write view_shape(numel, shape) that does what view does with -1: given the number of elements and a target shape that may contain one -1, return the shape with the -1 replaced. Raise ValueError if there is more than one -1, or if the elements do not fit the shape exactly.

Exercise
def view_shape(numel, shape):
    return shape
Hint

Multiply the sizes that are not -1 (`math.prod`). With one -1, the missing size is `numel // known`, and `numel % known` must be 0. Without a -1, the product must equal `numel`.

3A gradient by nudging

Write numeric_grad(f, xs, h=1e-5) that estimates the gradient of f (a function of a list of numbers that returns one number) at the point xs: for each position i, nudge only xs[i] up and down by h and return the list of slopes (f(up) - f(down)) / (2 * h). Do not change the list you were given. This is how people check that autograd is right.

Exercise
def numeric_grad(f, xs, h=1e-5):
    return [0.0 for _ in xs]
Hint

For each i, make two copies with `list(xs)`, add `h` to one copy's element i and subtract `h` from the other's, then apply the slope formula.

Interview questions

Q1What is the difference between a PyTorch tensor and a NumPy array?

Both are n-dimensional arrays with a shape and a dtype, and they share indexing and broadcasting rules. A tensor can also live on a GPU (cuda, mps) and can record operations for autograd. PyTorch defaults to float32 where NumPy uses float64, and torch.from_numpy / .numpy() convert between them without copying.

Q2How does autograd work?

Tensors with requires_grad=True record every operation applied to them in a graph. Calling backward() on a scalar loss walks the graph in reverse, applying the chain rule, and stores d(loss)/d(tensor) in each leaf tensor's .grad. Gradients accumulate, so they are zeroed before each step.

Q3Why and when do you use torch.no_grad()?

For anything that is not training: inference, evaluation, embedding, and the weight update itself. It stops PyTorch recording the graph, which saves memory and time, and avoids errors from in-place changes to tensors that require grad.

Q4What is the difference between view and reshape?

view returns a tensor with a new shape over the same memory and fails if the memory layout does not allow it (for example after a transpose). reshape returns a view when possible and silently copies otherwise. .contiguous() makes a copy with a standard layout.

Q5How do you write PyTorch code that runs on a GPU when there is one?

Pick the device once (cuda if torch.cuda.is_available(), else mps on Apple silicon, else cpu), move the model and every input batch to it with .to(device) and keep the results, create new tensors with device=device, and bring results back with .cpu() before converting to NumPy or Python.