PyTorch primer1 / 6

Lesson 1 · Tensors and linear algebra

Tensors

The problem

In the maths chapters you worked out delivery times by hand. Delivery B is 5 km with traffic level 1. With weights of 4 minutes per km and 6 per traffic level, the dot product gives 4×5+6×1=264 \times 5 + 6 \times 1 = 26 minutes.

A real model does this for thousands of deliveries and thousands of weights. You need a way to store all those numbers and do maths on them quickly. In PyTorch, that's a tensor. This chapter shows the numbers from vectors, matrices and numerical integration coming out of code.

Making a tensor

A tensor is a grid of numbers. Each direction of the grid is an axis. A vector is a tensor with one axis. A matrix is a tensor with two.

torch.tensor makes one from a Python list. A list of rows makes a matrix:

The deliveries as tensors
# One delivery: 5 km, traffic level 1. And the weights: minutes per km, minutes per level.
x = torch.tensor([5.0, 1.0])
w = torch.tensor([4.0, 6.0])

print(x.shape)  # torch.Size([2])  -> one axis with 2 entries
print(x.dtype)  # torch.float32    -> the default for decimal numbers

# Three deliveries, one per row: a list of rows makes a tensor with two axes.
X = torch.tensor([
    [2.0, 0.0],  # A: 2 km, traffic 0
    [5.0, 1.0],  # B: 5 km, traffic 1
    [3.0, 2.0],  # C: 3 km, traffic 2
])
print(X.shape)  # torch.Size([3, 2])  -> 3 rows, 2 columns
print(X.ndim)   # 2                   -> the number of axes

Every tensor carries two facts with it:

  • shape says how many entries there are along each axis. torch.Size([3, 2]) means 3 rows and 2 columns, the maths shape (3×2)(3 \times 2). .ndim is the number of axes.
  • dtype says what kind of number the entries are. torch.float32 means 32-bit decimal numbers. It's PyTorch's default for decimals. Pass dtype=torch.float64 when you want 64-bit floats, which carry about 16 significant digits instead of about 7.

When code breaks, print .shape first. Most bugs in PyTorch code are shape bugs.

Whole numbers are a trap

Predict first

You write counts = torch.tensor([5, 1]), with no decimal points. What is counts.dtype?

Integer tensors behave differently from float ones:

Integer tensors
counts = torch.tensor([5, 1])  # whole numbers in, whole-number tensor out
print(counts.dtype)            # torch.int64
print(counts / 2)              # tensor([2.5000, 0.5000])  -> / always gives floats
print(counts // 2)             # tensor([2, 0])            -> // rounds down and stays int64
print(torch.sqrt(counts))      # tensor([2.2361, 1.0000])  -> entry-by-entry maths is fine
# counts.mean()                # error: "Input dtype must be either a floating point or complex dtype"
# torch.linalg.vector_norm(counts)  # error: "Expected a floating point or complex tensor"
print(counts.float().mean())   # tensor(3.)  -> convert first

counts[0] = 2.7                # store a decimal in an int64 tensor...
print(counts)                  # tensor([2, 1])  -> ...and it quietly keeps 2
  • / always gives decimals, even on integers. // rounds down and keeps integers.
  • Entry-by-entry maths like torch.sqrt accepts integers and returns floats.
  • .mean() and everything in torch.linalg refuse integers. .float() converts a tensor to float32 first.
  • Storing 2.7 in an int64 tensor quietly keeps 2. There's no warning.

So for maths, write 5.0, not 5.

Other ways to make tensors

These functions save typing:

Ready-made tensors
print(torch.linspace(0.0, 12.0, steps=7))  # tensor([ 0.,  2.,  4.,  6.,  8., 10., 12.])
print(torch.arange(5))                     # tensor([0, 1, 2, 3, 4])  -> stops before 5, int64
print(torch.arange(0.0, 1.0, 0.25))        # tensor([0.0000, 0.2500, 0.5000, 0.7500])
print(torch.zeros(3))                      # tensor([0., 0., 0.])
print(torch.ones(2, 3).shape)              # torch.Size([2, 3])
print(torch.eye(2))                        # tensor([[1., 0.], [0., 1.]])  -> the identity matrix
  • torch.linspace(start, end, steps=n) gives nn evenly spaced numbers, both ends included. steps counts numbers, not gaps. So linspace(0, 12, steps=7) is 0, 2, …, 12.
  • torch.arange(n) gives 0,1,…,n−10, 1, \dots, n - 1. Like Python's range, it stops before the end. With whole-number inputs it makes int64. Give it a decimal, like arange(6.0), to get floats.
  • torch.zeros and torch.ones fill a shape with 0s or 1s. Pass the sizes: torch.ones(2, 3) has shape (2, 3).
  • torch.eye(n) is the n×nn \times n identity matrix. "eye" sounds like I, the identity.

Indexing: counting from 0

The maths counts rows and columns from 1, so X32X_{32} is row 3, column 2. PyTorch counts from 0, like all of Python. So the same entry is X[2, 1].

Pick an expression below and watch which entries it reads.

0: km1: traffic
0 (A)20
1 (B)51
2 (C)32
X, with PyTorch's 0-based positions

X[1] → tensor([5., 1.])

shape torch.Size([2])

In maths: row 2 of X: delivery B.

Each expression reads some entries of X. A plain number removes its axis; a slice with a colon keeps it.

The rules:

  • X[i] is row i. Row 1 is the second row, delivery B.
  • X[i, j] is one entry. X[:, j] is column j. The : means "every row".
  • X[a:b] is a slice: rows a up to, but not including, b.
  • X[-1] counts from the end: the last row.

Predict first

X has shape (3, 2). What is the shape of X[:, 0]?

Picking one entry still gives a tensor, like tensor(2.). It has no axes, so its shape is torch.Size([]). To get a plain Python number, call .item(). You'll need it to print a loss or store it in a list.

Entry by entry, or @

Ordinary maths signs work entry by entry. 4.0 * km multiplies every entry by 4. km**2 squares every entry. So a function written for one number works on a whole tensor of inputs at once:

One function, many inputs
def delivery_time(km: torch.Tensor) -> torch.Tensor:
    """The machine from 1.1: 5 minutes to prepare, then 4 minutes per km."""
    return 5.0 + 4.0 * km


km = torch.linspace(0.0, 10.0, steps=11)
print(delivery_time(km))  # tensor([ 5.,  9., 13., ..., 45.])  -> every entry at once
print(torch.exp(torch.tensor([0.0, 1.0, 2.0])))  # tensor([1.0000, 2.7183, 7.3891])
print(torch.log(torch.tensor([0.0, -1.0])))       # tensor([-inf, nan])  -> no error raised

print(x * w)  # tensor([20.,  6.])  -> matching entries multiplied: still a vector
print(x @ w)  # tensor(26.)         -> the dot product: one number
  • torch.exp and torch.log are exe^x and the natural log ln⁡\ln, entry by entry (see exponentials and logs).
  • The log of 0 is -inf (minus infinity), and the log of a negative number is nan (not a number). PyTorch doesn't raise an error. These values spread silently through later sums.

* is not the dot product

x * w multiplies matching entries and gives a vector: tensor([20., 6.]). The dot product also adds them up: x @ w is tensor(26.). If you expected one number and got a vector, you probably used *.

The @ sign is matrix multiplication. It does every product from the maths chapters:

Dot products and matrix products
W = torch.tensor([
    [4.0, 5.0],  # minutes per km:            scooter, bike
    [6.0, 2.0],  # minutes per traffic level: scooter, bike
])
print(X @ w)  # tensor([ 8., 26., 24.])  -> (3, 2) @ (2,) -> (3,): one time per delivery
print(X @ W)  # (3, 2) @ (2, 2) -> (3, 2): one row per delivery, one column per vehicle
print(X.T)    # (2, 3): the transpose
# X @ X       # RuntimeError: mat1 and mat2 shapes cannot be multiplied (3x2 and 3x2)

cos = (x @ w) / (torch.linalg.vector_norm(x) * torch.linalg.vector_norm(w))
print(cos.item())  # 0.7071...: cos 45°, so x and w are 45° apart

The last lines use these to compute cosine similarity. Notice the comments like # (3, 2) @ (2,) -> (3,). Writing shapes next to a line is the quickest way to catch a mismatch. The next chapter is all about shapes.

Predict first

X has shape (3, 2). What does X @ X do?

Adding up along an axis

A reduction turns many numbers into fewer. .sum() with no arguments adds every entry and leaves a tensor with no axes.

Usually you want to add along one axis only. Below, parts holds the minutes from distance and from traffic for each delivery. It's X * w: each row of X times the weights. (The next chapter explains how * handles the different shapes.)

from kmfrom traffic
A80
B206
C1212
X * w (3, 2)
total
8
26
24
shape (3,)

Add across each row: one total per delivery (8, 26, 24).

Axis 1 disappears: shape (3, 2) → (3,). mean(dim=1) gives (4, 13, 12).

sum(dim=1) adds across each row, so the columns disappear: one total per delivery. sum(dim=0) adds down each column, so the rows disappear: one total per feature.

The rule: the axis you name is the one that disappears.

Sums and means along an axis
parts = X * w  # minutes from distance and from traffic, per delivery; shape (3, 2)
print(parts.sum())            # tensor(58.)               -> every entry: no axes left
print(parts.sum(dim=1))       # tensor([ 8., 26., 24.])   -> across each row: axis 1 disappears
print(parts.sum(dim=0))       # tensor([40., 18.])        -> down each column: axis 0 disappears
print(parts.mean(dim=0))      # tensor([13.3333,  6.0000])
print(parts.sum(dim=1, keepdim=True).shape)  # torch.Size([3, 1]) -> keep the axis, size 1
print((X @ W).argmin(dim=1))  # tensor([0, 0, 1])  -> the faster vehicle for A, B, C
  • parts.sum(dim=1) removes axis 1, leaving one time per delivery: (8,26,24)(8, 26, 24). That's XwX\mathbf{w} again, built in two steps.
  • parts.sum(dim=0) removes axis 0: (40,18)(40, 18). So 40 of the 58 minutes come from distance.
  • .mean(dim=…) averages instead of adding.
  • keepdim=True keeps the axis with size 1, so (3, 2) becomes (3, 1), not (3,).
  • .argmin(dim=1) gives the position of the smallest entry in each row. Here it picks the faster vehicle for each delivery: the scooter (0) for A and B, the bike (1) for C.

Predict first

times has shape (1000, 2): 1000 deliveries, 2 vehicles. What shape is times.mean(dim=0)?

Integrals are reductions too

In numerical integration, you estimated the scooter's distance from speed samples. Each trapezoid's area is its average height times its width. Adding them up is one more reduction.

024681012010203040t (minutes)v (km/h)

Press play. t has 7 samples, so there are 6 trapezoids.

cumulative_trapezoid(v, t) / 60 = […]

Trapezoids added: 0 of 6
Step through torch.cumulative_trapezoid. Each step adds one trapezoid between neighbouring samples. The last running total is what torch.trapezoid returns.

With samples every 2 minutes, the trapezoids add up to 3.52 km. Switch to 1-minute samples and the total moves closer to the exact 3.8 km.

Here is the same calculation with 121 samples, 0.1 minutes apart. speed(t) is the scooter's speed curve from 1.10, written as a helper function in the full file. It works entry by entry, so v holds one speed per sample time.

Distance from speed samples
t = torch.linspace(0.0, 12.0, steps=121, dtype=torch.float64)  # every 0.1 minutes
v = speed(t)                                                   # (121,): km/h at each time

km_total = torch.trapezoid(v, t) / 60             # km/h × minutes ÷ 60 = km
print(km_total)                                   # tensor(3.7987, dtype=torch.float64); exact 3.8
print(torch.trapezoid(v) / 60)                    # tensor(37.9870, ...): no x, so spacing 1. Wrong!

odometer = torch.cumulative_trapezoid(v, t) / 60  # (120,): the total after each slice
print(odometer.shape, odometer[-1])               # torch.Size([120]) and the final 3.7987 km
  • torch.trapezoid(y, x) adds up the trapezoids under samples y, taken at points x. Speed is in km/h and time in minutes, so we divide by 60 to get km.
  • torch.cumulative_trapezoid(y, x) gives the running total after each trapezoid. It has one entry fewer than y.

Predict first

You forget the x and write torch.trapezoid(v) / 60. The samples are 0.1 minutes apart. What comes out?

The full file is in python/examples/02-pytorch-primer/01-tensors/tensors.py. Run it from the python/ folder with uv run python examples/02-pytorch-primer/01-tensors/tensors.py.

Common misconceptions

"torch.tensor and torch.Tensor are the same." torch.tensor(...) with a small t is the function that makes a tensor. torch.Tensor with a capital T is the type, used in type hints like def f(x: torch.Tensor) -> torch.Tensor.

"X[1] is the first row." It's the second. PyTorch counts from 0.

"A shape of (3,) is a column." It has one axis, so it's neither a row nor a column. The next chapter shows how to turn it into either.

"dim=0 gives one answer per row." The axis you name disappears. sum(dim=0) removes the rows and gives one answer per column.

Recap

  • A tensor is a grid of numbers with a shape and a dtype. Write 5.0, not 5, to get floats.
  • PyTorch counts from 0, so the maths X32X_{32} is X[2, 1].
  • *, + and functions like torch.exp work entry by entry. @ does dot products and matrix products.
  • sum(dim=d) removes axis d.
  • torch.trapezoid(y, x) integrates samples. Pass x.
  • PyTorch names: torch.tensor, .shape, .ndim, .dtype, .float(), .item().
  • More PyTorch names: torch.linspace, torch.arange, torch.zeros, torch.ones, torch.eye, indexing and slices.
  • Maths in PyTorch: torch.exp, torch.log, @, .T, torch.linalg.vector_norm; .sum, .mean and .argmin with dim= and keepdim=; torch.trapezoid and torch.cumulative_trapezoid.