Skip to main content

AI and machine learning · Beginner · 22 min

Learn PyTorch tensors and autograd

By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · PyTorch 2.15.0 (CPU) · NumPy 2.5.5

You will create and reshape PyTorch tensors, move data to and from NumPy, get gradients with backward(), and fit a straight line to 200 delivery trips with plain gradient descent on a CPU.

On this page

Every PyTorch model, from a two-number line fit to a large language model, is built from the same two pieces. A tensor holds numbers in a grid of any number of dimensions, much like a NumPy array, but it can live on a GPU. Autograd records the arithmetic you do with tensors and, when you call backward(), works out how much each input should change to make a result smaller. Training a model is those two pieces in a loop.

In this tutorial you learn both on a laptop CPU. You create tensors and check their shape, dtype and device, reshape and slice them, let broadcasting line up different shapes, and pass data to and from NumPy. Then you ask autograd for gradients, see the two mistakes that zero_grad() and torch.no_grad() exist to prevent, and fit a straight line that predicts delivery time from distance with nothing but tensors and a dozen lines of gradient descent.

No GPU is needed. Everything here runs in a few seconds on a modest machine.

Step 1 · Create the project and install PyTorch for CPU

Make a throwaway folder and a virtual environment. Install NumPy from PyPI first, then PyTorch from PyTorch's own CPU wheel index, which skips the CUDA libraries the default Linux wheel pulls in:

Bash
mkdir -p ~/tensors-demo
cd ~/tensors-demo
python3 -m venv .venv
source .venv/bin/activate
pip install --quiet numpy==2.5.5
pip install --quiet torch==2.15.0 --index-url https://download.pytorch.org/whl/cpu

The PyTorch download is about 200 MB and takes up under 1 GB once installed. On prepaid mobile data, run it once on Wi-Fi; nothing later in this tutorial goes online. On Windows, activate the environment with .venv\Scripts\activate instead of source.

Check it worked

Bash
python -c "import torch, numpy; print(torch.__version__, numpy.__version__)"

On Linux the output is 2.15.0+cpu 2.5.5. The +cpu tag tells you the CPU-only build is installed. On macOS the version reads 2.15.0, because the macOS wheel has no CUDA variant to tell apart.

Step 2 · Create tensors and read their shape, dtype and device

Three properties answer most "why does this not work" questions in PyTorch: shape (how many numbers along each dimension), dtype (what kind of number) and device (which processor holds them). Create a few tensors and print all three:

Bash
cat > tensors.py <<'PY'
import torch

prices = torch.tensor([120.0, 95.5, 210.0, 80.0])  # a list of floats
counts = torch.tensor([[3, 1, 0], [2, 5, 4]])      # a nested list of whole numbers
zeros = torch.zeros(2, 3)
grid = torch.arange(12)

torch.manual_seed(0)
noise = torch.randn(3, 2)                           # random numbers, repeatable with the seed

for name, t in [("prices", prices), ("counts", counts), ("zeros", zeros), ("grid", grid), ("noise", noise)]:
    print(f"{name:<7} shape={tuple(t.shape)}  dtype={t.dtype}  device={t.device}")

print("noise:\n", noise)
print("counts as float:", counts.to(torch.float32).dtype)
print("int plus float gives:", (counts + 0.5).dtype)

device = "cuda" if torch.cuda.is_available() else "cpu"
moved = prices.to(device)
print("CUDA available:", torch.cuda.is_available(), "| prices now on:", moved.device)

assert prices.dtype == torch.float32 and counts.dtype == torch.int64
assert tuple(counts.shape) == (2, 3)
PY
python tensors.py

A few rules show up in that script:

  • Python floats become float32, PyTorch's default; Python integers become int64.
  • Mixing an integer tensor with a float promotes the result to float.
  • .to(device) returns a copy on another device. Operations between tensors need them on the same device, so models and data are moved together. On a machine without an NVIDIA GPU, device stays "cpu" and the same code still runs.

Check it worked

The first five lines show prices with shape (4,) and dtype torch.float32, counts with shape (2, 3) and dtype torch.int64, and every tensor on device=cpu. The noise tensor starts with 1.5410 because of manual_seed(0); run the script again and it prints the same numbers. The last line reads CUDA available: False | prices now on: cpu unless you have a CUDA GPU set up.

Step 3 · Reshape, slice and broadcast

Most bugs in model code are shape bugs, so practise on a small table where you can see every number:

Bash
cat > shapes.py <<'PY'
import torch

grid = torch.arange(12)
table = grid.reshape(3, 4)          # 3 rows, 4 columns, same 12 numbers
print("table:\n", table)
print("row 1:", table[1])
print("column 2:", table[:, 2])
print("bottom-right 2x2:\n", table[1:, 2:])
print("values above 6:", table[table > 6])

print("reshape(4, -1):", tuple(table.reshape(4, -1).shape))   # -1 means "work it out"
print("flatten:", tuple(table.flatten().shape))
print("unsqueeze(0):", tuple(table.unsqueeze(0).shape))       # add a batch dimension

row = torch.tensor([10, 20, 30, 40])   # shape (4,)
col = torch.tensor([[1], [2], [3]])    # shape (3, 1)
print("table + row:\n", table + row)
print("table * col:\n", table * col)

try:
    table + torch.tensor([1, 2, 3])
except RuntimeError as err:
    print("shape error:", str(err).splitlines()[0])

print("column means:", table.float().mean(dim=0))
print("row sums:", table.sum(dim=1))

assert (table + row)[2, 3].item() == 51
assert tuple(table.unsqueeze(0).shape) == (1, 3, 4)
PY
python shapes.py

Indexing works as in NumPy: table[1] is a row, table[:, 2] is a column, and a boolean mask such as table > 6 picks out matching values. reshape keeps the numbers and changes how they are grouped; the total count must stay 12.

Broadcasting is how table + row works even though the shapes differ. PyTorch lines the shapes up from the right. A dimension of size 1, or one that is missing, is stretched to match the other tensor. So the (4,) row is added to each of the three rows, and the (3, 1) column multiplies each row by its own number. A (3,) tensor cannot be lined up against four columns, which is the error you see.

dim=0 in mean collapses the rows and leaves one value per column; dim=1 collapses the columns and leaves one per row.

Check it worked

table + row ends with the row [18, 29, 40, 51], and table * col ends with [24, 27, 30, 33] (the last row times 3). The shape error line names the mismatch: The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimension 1. Learn to read that message: it tells you which dimension disagrees and the two sizes.

Step 4 · Move data to and from NumPy

Data often arrives as NumPy arrays from pandas, scikit-learn or a CSV reader. There are two ways in, and they behave differently:

Bash
cat > bridge.py <<'PY'
import numpy as np
import torch

readings = np.array([21.5, 23.0, 19.8])   # NumPy's default float is float64

shared = torch.from_numpy(readings)        # shares memory with the array
copied = torch.tensor(readings)            # makes its own copy
print("from_numpy dtype:", shared.dtype)

readings[0] = 99.0
print("shared after edit:", shared)
print("copied after edit:", copied)

as_float32 = torch.from_numpy(readings).float()
print("float32 copy:", as_float32.dtype)

back = as_float32.numpy()
print("back to NumPy:", type(back).__name__, back.dtype)

w = torch.ones(3, requires_grad=True)
try:
    w.numpy()
except RuntimeError as err:
    print("numpy() refused:", str(err).split(".")[0])
print("detach first:", w.detach().numpy())

assert shared[0].item() == 99.0 and copied[0].item() == 21.5
PY
python bridge.py

torch.from_numpy wraps the same block of memory, so it is instant for large arrays, and a change on one side shows on the other. torch.tensor copies. Pick from_numpy for speed when you will not edit the array afterwards, and torch.tensor when you want the two kept apart.

The dtype comes across too: NumPy defaults to float64, PyTorch models default to float32. Call .float() before feeding NumPy data to a model, or you get a dtype mismatch error later.

Check it worked

shared after edit starts with 99.0000; copied after edit still starts with 21.5000. The last two lines show that numpy() refuses a tensor that autograd is tracking (Can't call numpy() on Tensor that requires grad), and that detach() gives you an untracked view of the same numbers, which NumPy accepts. You meet requires_grad properly in the next step.

Step 5 · Get a gradient with requires_grad and backward

Setting requires_grad=True on a tensor tells autograd to record every operation that uses it. Calling backward() on a single-number result then walks that record in reverse and stores, in each input's .grad, how fast the result changes when that input changes.

Start with something you can check by hand: y = x² + 3x. Its derivative is 2x + 3, which is 7 at x = 2.

Bash
cat > grads.py <<'PY'
import torch

x = torch.tensor(2.0, requires_grad=True)
y = x ** 2 + 3 * x
print("y =", y.item(), "| grad_fn:", type(y.grad_fn).__name__)

y.backward()
print("dy/dx at x=2:", x.grad.item())

# Two inputs: how wrong is the line minutes = w * km + b for three trips?
w = torch.tensor(1.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
km = torch.tensor([1.0, 2.0, 3.0])
minutes = torch.tensor([3.0, 5.0, 7.0])
loss = ((w * km + b - minutes) ** 2).mean()
loss.backward()
print(f"loss={loss.item():.4f}  dloss/dw={w.grad.item():.4f}  dloss/db={b.grad.item():.4f}")

assert x.grad.item() == 7.0
assert w.grad.item() < 0 and b.grad.item() < 0
PY
python grads.py

grad_fn is the label autograd attached to y: the last operation that produced it, linked back to the ones before. That chain is the graph backward() follows.

The second half is the part that matters for training. loss is the mean squared error of a guessed line through three trips that really follow minutes = 2 * km + 1. Both gradients are negative, which means the loss falls if w and b go up. That is the right direction: the guess of w = 1, b = 0 is too low on both.

Check it worked

The output is dy/dx at x=2: 7.0, matching the hand calculation, followed by loss=9.6667 dloss/dw=-13.3333 dloss/db=-6.0000. You can check the last line on paper: the errors are -2, -3, -4, their squares average to 29 / 3, and the gradient for b is twice the mean error, -6.

Step 6 · See why zero_grad and no_grad exist

Two behaviours of autograd trip up nearly everyone writing their first training loop. Run them deliberately so you recognise them:

Bash
cat > pitfalls.py <<'PY'
import torch

# 1. Gradients add up across backward() calls
x = torch.tensor(2.0, requires_grad=True)
for i in range(3):
    y = x ** 2 + 3 * x
    y.backward()
    print(f"after backward #{i + 1}: x.grad = {x.grad.item()}")

x.grad.zero_()
print("after zero_():", x.grad.item())

# 2. Changing a tracked tensor in place while autograd is recording is refused
w = torch.tensor(1.0, requires_grad=True)
loss = (w * 3 - 6) ** 2
loss.backward()
try:
    w -= 0.1 * w.grad
except RuntimeError as err:
    print("update refused:", str(err).split(".")[0])

with torch.no_grad():
    w -= 0.1 * w.grad
print("updated w:", round(w.item(), 4), "| still tracked:", w.requires_grad)

# 3. Arithmetic under no_grad is not recorded
with torch.no_grad():
    pred = w * 3
print("pred.requires_grad under no_grad:", pred.requires_grad)
print("pred.requires_grad normally:", (w * 3).requires_grad)

assert x.grad.item() == 0.0 and not pred.requires_grad
PY
python pitfalls.py

Gradients accumulate. Each backward() adds to .grad rather than replacing it, so the same calculation run three times reports 7, 14, 21. This is on purpose: it lets you add up gradients from several small batches before one update. In an ordinary loop it means you must clear the gradient after each update, with x.grad.zero_() here or optimizer.zero_grad() once you use an optimiser. Forget it and every step uses the sum of all past gradients, and training runs away.

Updates must not be recorded. PyTorch does not allow in-place changes, such as w -= ..., to a leaf tensor that requires grad while autograd is recording, because the change itself would be recorded as part of the model. Wrapping the update in with torch.no_grad(): tells autograd that this arithmetic is bookkeeping, not part of the model. The same block is what you use when making predictions after training: no graph is built, which saves memory and time.

Check it worked

The first three lines show x.grad climbing 7.0, 14.0, 21.0, then 0.0 after zero_(). The update line reads update refused: a leaf Variable that requires grad is being used in an in-place operation, and the version inside no_grad works: updated w: 2.8 | still tracked: True. Finally pred.requires_grad is False under no_grad and True without it.

Step 7 · Fit a straight line with gradient descent

Now put the pieces together. A courier service records 200 trips: distance in kilometres and time in minutes. The data is generated with a hidden rule, 2.5 minutes per kilometre plus 8 minutes for pick-up and drop-off, plus random delays. The model starts knowing nothing (w = 0, b = 0) and has to find the rule from the data.

Each pass through the loop does the same four things: predict, measure the loss, get gradients, and nudge w and b a small step against them.

Bash
cat > fit_line.py <<'PY'
import torch

torch.manual_seed(7)

# 200 trips: distance in km, time in minutes. Hidden rule: 2.5 min per km plus 8 min.
distance = torch.rand(200) * 20
minutes = 2.5 * distance + 8 + torch.randn(200) * 3

w = torch.zeros(1, requires_grad=True)   # minutes per km
b = torch.zeros(1, requires_grad=True)   # fixed minutes per trip
lr = 0.005                               # learning rate: how big each step is

for step in range(3001):
    pred = w * distance + b
    loss = ((pred - minutes) ** 2).mean()
    loss.backward()

    with torch.no_grad():
        w -= lr * w.grad
        b -= lr * b.grad
    w.grad.zero_()
    b.grad.zero_()

    if step % 500 == 0:
        print(f"step {step:>4}  loss {loss.item():8.3f}  w {w.item():.3f}  b {b.item():.3f}")

print(f"\nfitted: minutes = {w.item():.2f} * km + {b.item():.2f}")

with torch.no_grad():
    for km in [5.0, 12.0]:
        print(f"predicted time for {km:.0f} km: {(w * km + b).item():.1f} min")

assert abs(w.item() - 2.5) < 0.15 and abs(b.item() - 8) < 1.5
PY
python fit_line.py

The loss is the mean squared error, the average of the squared gaps between predicted and recorded times. The learning rate decides how far each step goes. Try lr = 0.02 and each step overshoots: the loss grows until the fit prints nan. Try 0.0005 and after 3,000 steps b has only reached about 4.3.

w learns fast because distances run up to 20 and give it a large gradient. b crawls, which is why the loop needs thousands of steps. Scaling the inputs to similar ranges, as you will do with real features, makes this much quicker.

Check it worked

The printed loss falls from about 1291.8 at step 0 to about 10.35 and then barely moves. The last block reads close to:

Text
fitted: minutes = 2.51 * km + 8.31
predicted time for 5 km: 20.9 min
predicted time for 12 km: 38.4 min

The model has recovered the hidden 2.5 and 8 to within the noise in 200 trips. The leftover loss of about 10 is the random delay you added (a spread of 3 minutes, squared, is 9); no straight line can predict that part.

To be sure gradient descent found the best line and not just a good one, compare it with the exact least-squares answer that PyTorch can solve directly:

Bash
cat > check_fit.py <<'PY'
import torch

torch.manual_seed(7)
distance = torch.rand(200) * 20
minutes = 2.5 * distance + 8 + torch.randn(200) * 3

X = torch.stack([distance, torch.ones(200)], dim=1)   # one column for km, one for the constant
solution = torch.linalg.lstsq(X, minutes.unsqueeze(1)).solution
print(f"least squares: minutes = {solution[0].item():.2f} * km + {solution[1].item():.2f}")
assert abs(solution[0].item() - 2.5) < 0.15, "slope should be close to 2.5"
PY
python check_fit.py

It prints least squares: minutes = 2.51 * km + 8.32. Your loop is within a hundredth on the intercept, still creeping towards it. For a straight line the exact formula is quicker; gradient descent earns its place on models with millions of weights, where no such formula exists and the same predict, loss, backward, update loop still works.

Step 8 · Clean up

When you have finished, leave the virtual environment and remove the project folder. This also frees the space PyTorch took:

Bash
deactivate
cd ~
rm -rf ~/tensors-demo
ls ~/tensors-demo 2>/dev/null || echo "removed"

Each tutorial in this series makes its own folder and virtual environment, so keeping this one saves nothing. When you install PyTorch again for the next tutorial, pip's cache usually makes the second install faster.

Check it worked

The last command prints removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.