PyTorch Basics
PyTorch is an open-source Python library for building and training neural networks, and the most widely used one in AI research and industry. It gives you three things NumPy doesn't: tensors that can run on a GPU, autograd, which computes gradients automatically, and ready-made layers, losses and optimizers.
Install it with pip install torch (the PyTorch website shows the right command for your computer and GPU).
What PyTorch Adds
| Feature | Description |
|---|---|
| Tensors | It is used to hold numbers in arrays of any shape, like NumPy arrays, on a CPU or a GPU |
| Autograd | It is used to compute gradients automatically: backpropagation for free |
torch.nn | It is used to build networks from layers like nn.Linear and nn.ReLU |
torch.optim | It is used to update weights with optimizers like SGD and Adam |
torch.utils.data | It is used to split data into shuffled batches |
Example: Tensors
A tensor is PyTorch's array. It works much like a NumPy array.
import numpy as np
import torch
scores = torch.tensor([[82.0, 64.0, 70.0],
[91.0, 77.0, 85.0]]) # 2 students, 3 quizzes
print(scores.shape, scores.dtype)
print("Mean per student:", scores.mean(dim=1))
print("Scaled to 0-1:", (scores / 100)[0])
weights = torch.tensor([0.2, 0.3, 0.5])
print("Weighted grade:", scores @ weights) # matrix times vector, as in NumPy
print("From NumPy:", torch.from_numpy(np.arange(3)), "| back to NumPy:", weights.numpy())
torch.manual_seed(0) # the same "random" numbers every run
print("Random 2x2:", torch.rand(2, 2))
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
print("Best device here:", device)torch.Size([2, 3]) torch.float32
Mean per student: tensor([72.0000, 84.3333])
Scaled to 0-1: tensor([0.8200, 0.6400, 0.7000])
Weighted grade: tensor([70.6000, 83.8000])
From NumPy: tensor([0, 1, 2]) | back to NumPy: [0.2 0.3 0.5]
Random 2x2: tensor([[0.4963, 0.7682],
[0.0885, 0.1320]])
Best device here: mpsExplanation: torch.tensor() makes a tensor from a list; its shape is [2, 3] (2 students, 3 quizzes), and its default type for decimals is float32, which uses half the memory of NumPy's float64 and is what GPUs are fastest at. mean(dim=1) averages across each row, and @ is matrix multiplication, exactly as in NumPy. torch.from_numpy() and .numpy() convert between the two libraries. torch.manual_seed(0) makes random numbers repeatable. The best device depends on the computer: mps here (an Apple silicon Mac's GPU), cuda on an NVIDIA GPU, otherwise cpu.
Example: Autograd
Autograd records every operation on tensors marked requires_grad=True, then computes all the gradients when you call .backward(). This is the same network and example as in "Backpropagation":
import torch
# The same tiny network and example as in "Backpropagation", now with autograd
x, target = torch.tensor([1.0, 2.0]), torch.tensor(1.0)
W1 = torch.tensor([[0.1, 0.4], [-0.3, 0.2]], requires_grad=True) # track gradients for these
b1 = torch.tensor([0.0, 0.1], requires_grad=True)
W2 = torch.tensor([0.5, -0.6], requires_grad=True)
b2 = torch.tensor(0.2, requires_grad=True)
h = torch.sigmoid(x @ W1 + b1)
y = h @ W2 + b2
loss = (y - target) ** 2
loss.backward() # backpropagation, done for you
print(f"loss {loss.item():.4f}")
print("Gradient for W2:", W2.grad.round(decimals=4))
print("Gradient for W1:", W1.grad.round(decimals=4))loss 1.0770
Gradient for W2: tensor([-0.7836, -1.4756])
Gradient for W1: tensor([[-0.2439, 0.2559],
[-0.4878, 0.5118]])Explanation: The forward pass is written as ordinary math. loss.backward() runs backpropagation through everything PyTorch recorded, and stores each gradient in the weight's .grad. The results, −0.7836 and −1.4756 for W2 and −0.2439, 0.2559, −0.4878, 0.5118 for W1, match the hand-written backward pass exactly. The twelve lines of chain rule from the previous lesson became one call.
Example: Building a Network Layer by Layer
import torch
from torch import nn
torch.manual_seed(0)
model = nn.Sequential(
nn.Linear(64, 32), # 64 inputs -> 32 hidden neurons: 64*32 weights + 32 biases
nn.ReLU(),
nn.Linear(32, 10), # 32 hidden -> 10 outputs, one score per digit 0-9
)
print(model)
print("Parameters to learn:", sum(p.numel() for p in model.parameters()))
batch = torch.rand(5, 64) # 5 made-up inputs of 64 numbers each
scores = model(batch)
print("Output shape:", scores.shape)
print("Chances for the first input:", torch.softmax(scores[0], dim=0).detach().numpy().round(2))Sequential(
(0): Linear(in_features=64, out_features=32, bias=True)
(1): ReLU()
(2): Linear(in_features=32, out_features=10, bias=True)
)
Parameters to learn: 2410
Output shape: torch.Size([5, 10])
Chances for the first input: [0.14 0.1 0.09 0.09 0.09 0.11 0.09 0.09 0.09 0.11]Explanation: nn.Sequential chains layers in order. nn.Linear(64, 32) is a fully connected layer: 64 × 32 = 2,048 weights plus 32 biases. With the second layer's 32 × 10 + 10 = 330, the network has 2,410 parameters, all created with small random starting values. Passing a batch of 5 inputs gives an output of shape [5, 10]: 10 scores per input, one per digit. Softmax turns the first input's scores into chances that add up to 1; they're all close to 0.1 because the network is untrained and has no idea yet. The next lesson trains it.
Common Tensor Operations
| Operation | Code |
|---|---|
| Create | torch.tensor([...]), torch.zeros(3, 4), torch.rand(2, 2) |
| Shape and type | t.shape, t.dtype |
| Reshape | t.reshape(4, 3), t.view(-1) |
| Math | t + 1, t * u, t @ u, t.mean(dim=0) |
| Largest value's position | t.argmax(dim=1) |
| Move to a device | t.to("cuda"), t.to("mps") |
| A plain Python number | t.item() |
Common Mistakes
Mixing devices. A tensor on the GPU can't be combined with one on the CPU; move both with .to(device).
Forgetting requires_grad. Without it, autograd doesn't track the tensor and .grad stays None.
Converting tensors that need gradients. Call .detach() before .numpy() on a tensor that is part of a gradient calculation, as in the softmax line above.
Mixing float64 and float32. NumPy arrays become float64 tensors; convert with dtype=torch.float32 for models.
Interview Corner
What is a tensor?
A multi-dimensional array of numbers, PyTorch's basic data structure. It's like a NumPy array but can live on a GPU and track operations for automatic gradients.
What does autograd do?
It records operations on tensors that require gradients, and computes all their gradients with backpropagation when .backward() is called on the result.
Practice
Exercise: a deeper network. Add another nn.Linear(32, 32) and nn.ReLU() in the middle of the nn.Sequential. How many parameters does it have now? Work it out by hand first.
Check your understanding:
- Why is PyTorch's default
float32instead offloat64? - Where are the gradients stored after
loss.backward()? - How did 2,410 parameters come from two
nn.Linearlayers?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Tensor | torch.tensor(data, dtype=torch.float32) |
| Track gradients | torch.tensor(..., requires_grad=True) |
| Backpropagation | loss.backward(), then w.grad |
| A network | nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10)) |
| Count parameters | sum(p.numel() for p in model.parameters()) |
Was this tutorial helpful?