3/23
Part 1 of 6 · From NumPy to PyTorchLearn and do

Already write PyTorch every day? Skip to Part 3, where the attention shapes start.

Tensors

Say you join a team that trains its models in PyTorch, and on day one someone sends you their attention code. Do you have to learn a new library before you can read it? Mostly not. A PyTorch tensor is the same grid of numbers as a NumPy array. Shapes, broadcasting, @, slicing and None all behave the way you know. What changes is a handful of names.

Here's the students' table from the NumPy lesson, now as a tensor:

import torch
from torch import nn

# Ana
scores = torch.tensor([[70., 80., 90.],
                       # Ben
                       [50., 100., 60.]])
print(scores.shape)
# each student's average
print(scores.mean(dim=1, keepdim=True))
torch.Size([2, 3])
tensor([[80.],
        [70.]])

Same table, same row averages. The only new thing is the spelling: NumPy says axis and keepdims, and PyTorch says dim and keepdim, with no s. Your NumPy habit won't hurt you here, because PyTorch quietly accepts keepdims too. Still, most code you'll read says keepdim, so that's the one to recognize.

More NumPy names in PyTorch
NumPyPyTorch
x.sum(axis=1, keepdims=True)x.sum(dim=1, keepdim=True)
np.swapaxes(k, -1, -2)k.transpose(-2, -1)
np.where(m, a, b), np.tril(a)torch.where(m, a, b), torch.tril(a)
np.concatenate([a, b], axis=1)torch.cat([a, b], dim=1)
np.random.default_rng(0)torch.manual_seed(0)

You don't need to memorize that table. Say what you want in words first, like add up each row and keep the row axis, and the right call follows. The thing that really matters is which axis.

Two small things show up everywhere:

print(scores.sum())
print(scores.sum().item())
tensor(450.)
450.0

A sum over everything is still a tensor, just one with no axes left. .item() turns it into a plain Python number, which is what you want when you print or log a loss.

In the editor, scores is the same table: Ana's row, then Ben's. Fill in student_totals, each student's total kept as a column, and test_totals, each test's total as one row of three numbers.