NumPy + PyTorch from scratch
contents
- NumPy primer
- the ndarray
- creating arrays
- ufuncs (element-wise ops)
- indexing and slicing
- views vs. copies
- squeeze, unsqueeze, view
- slicing + math
- reshaping and concatenating
- broadcasting
- three kinds of ops
- linear algebra
- PyTorch primer
- what happens when you call torch.add
- creating tensors
- PyTorch dimensions
- autograd
- how autograd works (pictures)
- data loaders
- forward pass and inference
- loading the dataset
- the model
- training loop
- doing it with raw matrices (no nn.Linear)
- model definition
- forward pass
- loss (cross-entropy)
- key gradient identity (softmax + cross entropy)
- backpropagation
- gradient descent update
- mapping to PyTorch code
- key insight
NumPy primer
NumPy gives you fast, fixed-type arrays in Python.
(Most visualizations in this section are from Jay Alammar's visual numpy guide
why not just use python lists?
Say you want a dot product of two million-element vectors. Pure Python:
import time
def python_dot(a, b):
"""Computes dot product of two lists."""
result = 0
for i in range(len(a)):
result += a[i] * b[i]
return result
# Let's try it with million-element lists
size = 1_000_000
list_a = list(range(size))
list_b = list(range(size))
start_time = time.time()
py_result = python_dot(list_a, list_b)
end_time = time.time()
print(f"Python dot product result: {py_result}")
print(f"Time taken with Python lists: {(end_time - start_time) * 1000:.2f} ms")Same thing with NumPy:
import numpy as np
# Let's try it with million-element NumPy arrays
array_a = np.arange(size)
array_b = np.arange(size)
start_time = time.time()
np_result = np.dot(array_a, array_b)
end_time = time.time()
print(f"NumPy dot product result: {np_result}")
print(f"Time taken with NumPy arrays: {(end_time - start_time) * 1000:.2f} ms")Run both. On an Apple M4 with NumPy 2.5.4, the Python loop takes 26.5 ms and np.dot takes 0.29 ms, about 90x faster. Why?
- NumPy arrays are dense, contiguous, fixed-type blocks of memory. Python lists are arrays of pointers to heap-allocated objects, so every element access follows a pointer.
- NumPy ops are vectorized: they run as C/Fortran loops under the hood (It runs at near-C speed)
the ndarray
Everything in NumPy revolves around the ndarray. You create one from a list:

matrix = np.array([[1, 2, 3],
[4, 5, 6]])Every array has a few attributes you'll use constantly:
.ndim: number of dimensions. Ourmatrixhas 2..shape: size along each dimension.(2, 3)= 2 rows, 3 columns..size: total element count. 6 here..dtype: data type. NumPy arrays are homogeneous: every element has the same type. This is what makes them fast.
print(f"Dimensions: {matrix.ndim}") # Prints: 2
print(f"Shape: {matrix.shape}") # Prints: (2, 3)
print(f"Size: {matrix.size}") # Prints: 6
print(f"Data type: {matrix.dtype}") # Prints: int64 (or similar, depending on your system)Set the dtype on creation or cast later with .astype() (returns a new array).
float_matrix = matrix.astype(np.float32)
print(f"New data type: {float_matrix.dtype}") # Prints: float32creating arrays
In practice you almost never build arrays from Python lists. You use these:

# Create an array of all zeros
zeros_array = np.zeros((2, 3))
print(f"Zeros:\n{zeros_array}\n")
# Create an array of all ones
ones_array = np.ones((3, 2), dtype=np.int16)
print(f"Ones:\n{ones_array}\n")
# Create a 2x2 identity matrix (1s on the diagonal)
identity_matrix = np.eye(2)
print(f"Identity:\n{identity_matrix}\n")
# Create an array with a range of elements (like Python's range)
ranged_array = np.arange(0, 10, 2) # Start, stop (exclusive), step
print(f"Ranged array: {ranged_array}\n")
# Create an array with evenly spaced numbers over an interval
linspace_array = np.linspace(0, 1, 5) # Start, stop (inclusive), number of points
print(f"Linspace array: {linspace_array}\n")ufuncs (element-wise ops)
Instead of writing this garbage:
matrix = np.array([[1, 2, 3], [4, 5, 6]])
new_matrix = np.zeros(matrix.shape)
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
new_matrix[i, j] = matrix[i, j] + 10You write:
matrix = np.array([[1, 2, 3], [4, 5, 6]])
new_matrix = matrix + 10
print(f"Matrix + 10:\n{new_matrix}")
Works for all basic arithmetic (+, -, *, /, **), and between two arrays of the same shape.

For aggregation (sum, min, max and others), use the axis parameter:

axis=0collapses rows (result per column).axis=1collapses columns (result per row).

x = np.array([[1, 2], [3, 4]])
print(f"Sum of all elements: {np.sum(x)}") # Prints: 10
print(f"Sum of each column: {np.sum(x, axis=0)}") # Prints: [4 6]
print(f"Sum of each row: {np.sum(x, axis=1)}") # Prints: [3 7]indexing and slicing
Python list slicing but for n-dimensions. You specify a slice per dimension, separated by commas.

basic slicing
a = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
# Get the first two rows and columns 1 and 2
# (row 0 and 1, column 1 and 2)
b = a[:2, 1:3]
print(f"Sliced array b:\n{b}") # Prints [[2 3], [6 7]]fancy indexing and boolean masks
Integer array indexing ("fancy indexing") takes arrays of indices and grabs the exact elements you want.
# Create an array
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
print(f"Original array a:\n{a}\n")
# Create an array of indices to select one element from each row
b_indices = np.array([0, 2, 0, 1])
# Select one element from each row of a using the indices in b
# This selects a[0,0], a[1,2], a[2,0], a[3,1]
selected = a[np.arange(4), b_indices]
print(f"Selected elements: {selected}") # Prints: [ 1 6 7 11]
# We can also use this to modify elements
a[np.arange(4), b_indices] += 100
print(f"\nModified array a:\n{a}")Boolean indexing filters elements by a condition. Very swag.
bool_idx = (a > 10) # This creates a boolean array!
print(f"\nBoolean mask (a > 10):\n{bool_idx}\n")
# Use the boolean mask to select only the elements that are > 10
print(f"Elements > 10: {a[bool_idx]}") # or just a[a > 10]views vs. copies
Basic slicing returns a view, not a copy.
ary = np.array([[1, 2, 3], [4, 5, 6]])
print(f"Original array:\n{ary}\n")
# Create a view of the first row
first_row_view = ary[0]
first_row_view += 100 # Modify the view
print(f"Modified first row: {first_row_view}")
print(f"\nOriginal array is CHANGED:\n{ary}")This is a performance thing: NumPy avoids copying huge arrays. If you want a copy, ask for one explicitly:
copied_first_row = ary[0].copy()
copied_first_row -= 50 # Modify the copy
print(f"\nModified copy: {copied_first_row}")
print(f"Original array is UNCHANGED:\n{ary}").reshape() also returns a view when the memory layout allows it, and a copy when it does not. The -1 trick lets NumPy infer one dimension: 12 elements + .reshape(3, -1) = (3, 4). PyTorch's .view() takes the same arguments but never copies.

# Create an array with initial shape
original = np.arange(12)
print("Original shape:", original.shape)
print("Original array:", original)
# Reshape using -1 trick
reshaped = original.reshape(2, -1)
print("\nReshaped to (2, -1):\n", reshaped)
print("New shape:", reshaped.shape) # Prints: (2, 6)squeeze, unsqueeze, view
Quick PyTorch preview, since these are the tensor version of reshape. A PyTorch tensor is the NumPy array of PyTorch: same idea, plus GPU support and gradients (more on tensors below).
unsqueeze(dim) adds a size-1 dimension, squeeze(dim) removes one. You'll use unsqueeze(0) constantly to add a batch dimension before feeding a single sample to a model.
import torch
# Create a tensor
tensor = torch.tensor([1, 2, 3, 4, 5])
print("Original shape:", tensor.shape)
print("Original tensor:", tensor)
# Add a dimension at position 0 (adds batch dimension)
with_batch = tensor.unsqueeze(0)
print("\nAfter unsqueeze(0):")
print("Shape:", with_batch.shape)
print("Tensor:\n", with_batch)
# Remove the dimension we just added
back_to_original = with_batch.squeeze(0)
print("\nAfter squeeze(0):")
print("Shape:", back_to_original.shape)
print("Tensor:", back_to_original)
# This is especially useful when there's a shape mismatch error between the model and the input data (common when working with single data points instead of batches).
# view is like .reshape in numpy - it lets you specify the desired shape of the tensor.
tensor = torch.tensor([0, 1, 2, 3, 4]) # tensor([0, 1, 2, 3, 4])
reshaped = tensor.view(5, 1) # Reshape to 5 rows, 1 column
print(reshaped.shape) # Output: torch.Size([5, 1])
# Same -1 trick as numpy: let PyTorch infer the size of that dimension
dynamic_reshaped = tensor.view(-1, 1)
print(dynamic_reshaped.shape) # Output: torch.Size([5, 1])slicing + math
tensor = torch.tensor([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])
second_row_third_column = tensor[1, 2] # second_row_third_column = tensor[1][2] same thing
last_row = tensor[-1]
second_row_third_column # tensor(7)
last_row # tensor([ 9, 10, 11, 12])
# Math operations
data = torch.tensor([10.0, 20.0, 30.0, 40.0, 50.0])
data.mean() # tensor(30.)
data.std() # tensor(15.8114): sample std, divides by N-1 (np.std divides by N and gives 14.1421)
# Dot Product
t1 = torch.tensor([1, 2, 3])
t2 = torch.tensor([4, 5, 6])
torch.dot(t1, t2) # tensor(32)
# 1 * 4 + 2 * 5 + 3 * 6
# 4 + 10 + 18
# 32
# Derivatives
x = torch.tensor(2.0, requires_grad=True) # tensor(2., requires_grad=True)
y = x ** 2 # tensor(4., grad_fn=<PowBackward0>)
y.backward() # x^2 derivative = 2x (2*2) = 4
x.grad # tensor(4.)x = 2, y = x^2, derivative of x^2 is 2x, so x.grad = 2 * 2 = 4. That's it. PyTorch did the calculus for you. The autograd section shows how.
reshaping and concatenating
You'll have to use this too many times bcs data is never in teh right shape.. Get used to this.
a = np.arange(12) # A 1D array of 0-11
print(f"Original: {a}\n")
# Reshape it into a 3x4 matrix
b = a.reshape(3, 4)
print(f"Reshaped to 3x4:\n{b}\n")
# Flatten it back to 1D
c = b.ravel() # ravel() creates a view if possible
d = b.flatten() # flatten() always creates a copy
print(f"Raveled: {c}\n")
# Transpose (swap rows and columns)
print(f"Transposed:\n{b.T}\n")
# visual: https://jalammar.github.io/images/numpy/numpy-transpose.png
# Join arrays together
ary1 = np.array([[1,2], [3,4]])
ary2 = np.array([[5,6]])
# Join along rows (axis=0)
print(f"Concatenated (axis 0):\n{np.concatenate([ary1, ary2], axis=0)}\n")
# Join along columns (axis=1) - shapes must match!
print(f"Concatenated (axis 1):\n{np.concatenate([ary1, ary1], axis=1)}\n")broadcasting
Broadcasting lets you do math on arrays of different shapes without writing loops. The simplest case is array + 5: NumPy broadcasts the scalar to every element.
More interesting: adding a vector to each row of a matrix.

# A 4x3 matrix
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
# A vector of shape (3,)
v = np.array([1, 0, 1])
# Add v to each row of x
y = x + v
print(f"Original matrix x:\n{x}\n")
print(f"Vector v: {v}\n")
print(f"Result of broadcasting y = x + v:\n{y}")NumPy compares the two shapes one dimension at a time, starting from the right. Two dimensions are compatible if they're equal or one of them is 1. If one shape is shorter, NumPy pads it with 1s on the left. Then NumPy "stretches" each size-1 dimension to match.
Figure: NumPy pads v from (3,) to (1, 3) and repeats it over the 4 rows of x. (4, 3) + (2, 1) fails at dim -2, because 4 and 2 differ and neither is 1.

Three more cases: a scalar plus a vector, a row over a 3x3 matrix, and a column plus a row.
three kinds of ops
Every op in this post is one of three kinds:
- Elementwise ops (add, multiply, ReLU) touch each number one time.
- Reduce ops (sum, max, mean) collapse a dimension into one number.
- Movement ops (view, transpose, expand, broadcasting) do no math at all. They change the shape and the strides and keep the same buffer.
Transpose a 1000×1000 array and look at the buffer:
x = np.ones((1000, 1000))
y = x.T
print(np.shares_memory(x, y)) # True: same memory
print(x.strides, y.strides) # (8000, 8) (8, 8000), in bytes: 8 bytes per float64
print(y.flags['C_CONTIGUOUS']) # Falsex.T copies nothing. It swaps the strides. PyTorch tensors work the same way. This is why views vs. copies matters, and why some ops call .contiguous() first.
linear algebra

m = np.array([[1,2,3], [4,5,6]]) # (2,3)
v = np.array([1,0,1]) # (3,)
# Matrix-vector multiplication
# The @ symbol is the modern, preferred way
result = m @ v
print(f"m @ v = {result}") # (2,3) @ (3,) -> (2,)
# For explicit matrix-matrix multiplication, shapes must be compatible
# (m, n) @ (n, p) -> (m, p)
m1 = np.arange(6).reshape(2,3)
m2 = np.arange(6).reshape(3,2)
print(f"\nMatrix multiplication:\n{m1 @ m2}")
# You can also use np.matmul(m1, m2)PyTorch primer
I ♥️ PyTorch.
internals

- The tensor library works like NumPy and adds GPU acceleration.
- The autograd library is the heart of PyTorch. No need to compute backprop by hand anymore!! PyTorch records a graph of the operations on your weights and biases. From that graph it computes their gradients, so updating the weights is easy.
- The deep learning (DL) library has prebuilt loss functions, models, datasets and optimizers.
what is a tensor?
Fancy word for a data container / array.
- Scalar is a tensor of rank 0
- Vector is tensor of rank 1
- Matrix is tensor of rank 2
How are they stored? A tensor is a mathematical concept. To represent it on a computer, we need a physical layout in memory. The most common layout puts the elements of the tensor contiguously in memory, one row after another.
The strides tell PyTorch how many elements to skip in memory to move one step along each dimension. In the 2x2 matrix below, the strides are [2, 1]. Skip 2 elements to get to the next row, and 1 to get to the next column.

A matrix is a 2D tensor. Each int32 element takes 4 bytes, so the addresses go up by 4.

The same idea in 3D. Every tensor carries sizes, strides, a dtype, a device and a layout.
- When you call an operation (like
torch.dot(x, y)), PyTorch does two dispatches internally:- The first dispatch picks the implementation for the device and layout (the CPU kernel or the CUDA kernel).
- The second dispatch picks the code for the dtype (float, double, int). This dispatch is a switch statement over the dtypes that the kernel supports.
- You need both: the CPU (or CUDA) code that multiplies floats is different from the code that multiplies ints.

- The device says where the tensor's physical memory is. Examples: a CPU, an NVIDIA GPU (cuda), an AMD GPU (hip) or a TPU (xla). Each device has its own allocator, and that allocator doesn't work with any other device.
- The layout says how PyTorch interprets this physical memory. The most common layout is a strided tensor (sizes plus strides map the mathematical tensor to memory, as above). Sparse tensors use a different layout: a pair of tensors, one for indices and one for data. MKL-DNN tensors can use a blocked layout, which strides can't represent.
- The dtype says what each element of the tensor stores. This could be floats or integers, or, for example, quantized integers.
what happens when you call torch.add
Python parses the arguments. The dispatcher then routes the call to the kernel for the device, layout and dtype, and that kernel (CPU or CUDA) does the work.
Measure it. On my M4 (PyTorch 2.14.1, CPU, one thread):
| Elements | torch.add time | Per element |
|---|---|---|
| 1 | 0.38 µs | 379 ns |
| 1,000 | 0.42 µs | 0.42 ns |
| 1,000,000 | 262 µs | 0.26 ns |
1 element and 1,000 elements take almost the same time. So for small tensors, almost all of the time is Python and the dispatcher, not math. At 1,000,000 elements the math wins. This is why frameworks fuse kernels and we train in batches. Pretttty cooool no?
creating tensors
Take a cricketer, Virat Kohli. A Virat Kohli tensor would have multiple dimensions (Batting, Bowling, Fielding, Coaching), so it becomes a big matrix of these features and their values.
# How to create tensors and play with them
tensor0d = torch.tensor(1)
tensor1d = torch.tensor([1,2,3])
tensor2d = torch.tensor([[1, 2], [3, 4]])
tensor3d = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(tensor3d.dtype) # torch.int64 (PyTorch's default dtype for Python integers)
print(tensor2d.shape) # torch.Size([2, 2]) matrix of 2x2
# You can reshape arrays (returns a new tensor, does not mutate)
print(tensor2d.reshape(1, 4))
matrix1 = torch.tensor([
[1, 2, 3],
[4, 5, 6]
]) # shape = 2 * 3
print(matrix1.shape)
print(matrix1.reshape(3,2)) # opposite (we do this a lot while multiplying matrices since we need (p,q) * (q, m) so q = q for them to be multiplied (here p,q,q,m are rows and columns of two matrices))
'''
This prints matrix of 3 * 2 while preserving all elements and now we can use this to multiply to a matrix of (2 x whatever)
tensor([[1, 2],
[3, 4],
[5, 6]])
'''- Instead of reshape you can use view. It gives the same result here.
print(matrix1.view(3,2))The .view() method reshapes a tensor without copying the data. It's a "free" operation. The catch: it only works when the strides allow it. matrix1.T.view(6) raises a RuntimeError (view size is not compatible with input tensor's size and stride), and .reshape() falls back to a copy in that case.
- For transposing matrices we can use .T
matrix2 = matrix1.T # 3 * 2
multiply = matrix1 @ matrix2 # (2 * 3) * (3 * 2) = final matrix (2 * 2)
print(f"After multiplication: {multiply} of shape {multiply.shape}")After multiplication: tensor([[14, 32],
[32, 77]]) of shape torch.Size([2, 2])
Matrix1 = [
[1,2,3]
[4,5,6]
]
Matrix2 = [
[1, 4],
[2, 5],
[3, 6]
]
Matrix1 * Matrix2 = each elem of a row of m1 gets multiplied with the matching elem of a col of m2, and the products are added
{1*1 + 2*2 + 3*3} = {14} which is the first number
Similarily
{1 * 4 + 2 * 5 + 3 * 6} = {32} which is the second number
and so on...PyTorch dimensions
tensor = torch.tensor([1,2,3,4,5])
print(tensor.shape) # torch.Size([5])
s = torch.sum(tensor,dim=0)
print(s, s.shape) # scalar has no shape
# tensor(15) torch.Size([])More operations
tensor = torch.tensor([
[1,2,3], [4,5,6]
]) # 2x3
print("Dimension 0")
dimo0 = torch.sum(tensor, dim=0) # adds both lists (1 + 4, 2 + 5, 3 + 6)
print(dimo0)
print()
print("Dimension 1")
dimo1 = torch.sum(tensor, dim=1) # adds inner list (1+2+3, 4+5+6)
print(dimo1)
print("Inner most (just like last access in list)")
dims = torch.sum(tensor, dim=-1)
print(dims)
'''
Dimension 0
tensor([5, 7, 9])
Dimension 1
tensor([ 6, 15])
Inner most (just like last access in list)
tensor([ 6, 15])
'''
# 3d!!
tensor = torch.tensor([
[ [1,2,3], [4,5,6] ],
[ [7,8,9], [10,11,12] ]
])
print(tensor.shape) # 2 outer dimensions, each has 2 elements (2,2,3)autograd
PyTorch's autograd computes gradients for you. As your code runs, it builds a dynamic computation graph: a directed graph of every operation you run. No manual calculus. (The stackgrad post builds one from scratch.)
how autograd works (pictures)
The drawings below are from Edward Yang's PyTorch internals post.

Each tensor that takes part in autograd carries an AutogradMeta: its gradient and the function (grad_fn) that created it.

Every operation on a tensor that requires gradients adds a node to the graph. loss.backward() walks the graph from Sum back to the inputs.

The engine runs the backward graph. A function runs as soon as all the gradients it needs have arrived.
- PyTorch frees the graph after
.backward()to save memory. Setretain_graph=Trueif you need to run backward through it again. - Call
.backward()on the loss and PyTorch computes the gradients of all leaf tensors (tensors you created withrequires_grad=True, not results of operations). It stores them in.grad. Hence the name autograd.
Create neural net:
- Subclass
torch.nn.Module. Define layers in__init__, wire them up inforward.
model
class NeuralNetwork(torch.nn.Module):
def __init__(self, num_inputs, num_outputs):
super().__init__()
self.layers = torch.nn.Sequential(
# 1st hidden layer
torch.nn.Linear(num_inputs, 30),
torch.nn.ReLU(),
# 2nd hidden layer
torch.nn.Linear(30, 20),
torch.nn.ReLU(),
# output layer
torch.nn.Linear(20, num_outputs),
)
def forward(self, x):
return self.layers(x) # raw logits
print(NeuralNetwork(50, 3))NeuralNetwork(
(layers): Sequential(
(0): Linear(in_features=50, out_features=30, bias=True)
(1): ReLU()
(2): Linear(in_features=30, out_features=20, bias=True)
(3): ReLU()
(4): Linear(in_features=20, out_features=3, bias=True)
)
)- Linear layer = y = xW^T + b. That’s a fully connected / feedforward layer.
- Use
manual_seedfor reproducible weight init. grad_fn=<AddmmBackward0>= this tensor came from a matmul + add. Addmm = Add + matrix multiply.- At inference time, skip graph construction with
torch.no_grad(). It saves memory, and you don’t need gradients there. - Convention: models return raw logits (unnormalized scores, one per class). Apply softmax yourself at inference time for class probabilities (formula below).
data loaders
Custom dataset class -> DataLoader wraps it -> handles batching, shuffling, parallel loading.
num_workers
num_workers=0 means data loading happens in the main process. For small datasets this is fine. For anything real on a GPU, set it higher. Otherwise the GPU sits idle waiting for the next batch while the CPU fetches data. With num_workers > 0, worker processes load batches in the background while the model trains.
validation set
There’s usually a third split: the validation set, for tuning hyperparameters. You can peek at it repeatedly while tweaking. The test set you look at once. Otherwise you’re cheating.
model.train()/model.eval()toggle training vs eval mode. Dropout and batchnorm behave differently in each mode.- Call
optimizer.zero_grad()every step. PyTorch accumulates gradients by default.
Back to autograd. A one-neuron logistic regression: weight times input, plus bias, through a sigmoid, into a binary cross-entropy loss.
import torch
import torch.nn.functional as F
target = torch.tensor([1.0])
input = torch.tensor([1.1])
weight = torch.tensor([1.2])
bias = torch.tensor([0.0])
# y = mx + c
forward_pass = input * weight + bias
# applying activation function to this
prediction = torch.sigmoid(forward_pass)
loss = F.binary_cross_entropy(prediction, target)
print(loss) # tensor(0.2368) So we have a loss of 0.23 (our goal is to minimise this but that is for later)This is how the graph for this looks like:

- If any leaf node has
requires_grad=True, PyTorch builds the computation graph for you. Gradients flow through it via backprop (chain rule).

Start from the loss, work backward to the input. Compute dL/d(each parameter). Use those gradients to update weights via gradient descent.
- Gradient = vector of all partial derivatives of a function.
- Chain rule lets you decompose the gradient through a graph of operations.
The NN post does this by hand in NumPy. Here PyTorch does it for us:
import torch
import torch.nn.functional as F
from torch.autograd import grad
target = torch.tensor([1.0])
input = torch.tensor([1.1])
weight = torch.tensor([1.2], requires_grad=True) # we need to save this and bias for it to compute partial derivative
bias = torch.tensor([0.0], requires_grad=True)
# y = mx + c
forward_pass = input * weight + bias
# applying activation function to this
prediction = torch.sigmoid(forward_pass)
loss = F.binary_cross_entropy(prediction, target)
grad_loss_weight = grad(loss, weight, retain_graph=True)
grad_loss_bias = grad(loss, bias, retain_graph=True)
print(grad_loss_weight, grad_loss_bias) # (tensor([-0.2319]),) (tensor([-0.2108]),) [We need to update the weights and bias in the opposite direction of this (shift this) so that loss becomes minimum (same thing we were doing in numpy)]
grad() needs one call per parameter. loss.backward() fills .grad for every leaf in one go (here with weight 2.2 instead of 1.2):
y = torch.tensor([1.0]) # true label
x1 = torch.tensor([1.1]) # inp
w1 = torch.tensor([2.2], requires_grad=True)
b = torch.tensor([0.0], requires_grad=True)
z = x1 * w1 + b
a = torch.sigmoid(z)
loss = F.binary_cross_entropy(a, y)
print(loss) # tensor(0.0852, grad_fn=<BinaryCrossEntropyBackward0>)
grad_L_w1 = grad(loss, w1, retain_graph=True)
print(f"Gradient of Loss wrt Weight: {grad_L_w1}") # (tensor([-0.0898]),)
grad_L_b = grad(loss, b, retain_graph=True)
print(f"Gradient of Loss wrt Bias: {grad_L_b}") # (tensor([-0.0817]),)
loss.backward() # instead of doing all that jazz, just call this
print(w1.grad) # same results: tensor([-0.0898])
print(b.grad) # tensor([-0.0817])Trainable params live in nn.Linear layers (y = xW^T + b). Weights get initialized with small random numbers, different every time unless you seed with manual_seed.
Randomness shows up in many places: parameter init, dropout, data ordering. For reproducible runs (and sane debugging), set the seed in all three libraries at once:
seed = 0
torch.manual_seed(seed) # Torch
import numpy as np
np.random.seed(seed) # NumPy
import random
random.seed(seed) # Python
torch.manual_seed(42)
model = NeuralNetwork(50, 3)
print(model.layers[0].weight) # weights of first linear layer (weights and biases)
'''
Parameter containing:
tensor([[ 0.1081, 0.1174, -0.0331, ..., 0.0253, 0.0718, -0.0862],
[-0.1400, -0.0546, -0.1085, ..., -0.0477, -0.0501, -0.1368],
[-0.0810, 0.0353, -0.0187, ..., 0.1142, 0.1288, -0.1121],
...,
[-0.0031, -0.0573, 0.0515, ..., 0.0271, -0.0928, -0.1175],
[-0.0444, -0.1318, -0.0660, ..., 0.0647, -0.1230, -0.0531],
[ 0.0023, -0.1223, 0.0797, ..., 0.0369, 0.0862, 0.1328]],
requires_grad=True)
'''
X = torch.rand((1, 50)) # random input tensor
y = model(X) # forward pass
print(y) # 3 outputs
# tensor([[ 0.1136, -0.0523, -0.1083]], grad_fn=<AddmmBackward0>)
# Addmm stands for matrix multiplication (mm) followed by an addition (Add) Which is the same as y = mx + c (forward pass)forward pass and inference
Forward pass = input goes in, flows through all layers, output comes out.
At inference time you don't need gradients or the computation graph. Wrap the call in torch.no_grad() to save memory:
model = NeuralNetwork(50, 3) # 50 inp, 3 out
X = torch.rand((1, 50)) # random input tensor
with torch.no_grad():
output = model(X)
print(output)
# tensor([[-0.3570, -0.0455, -0.0394]]) (there is no grad function here we aren't saving it, we are just computing and printing output of our network which is what we need at inference time)
Raw logits are useless for interpretation. Apply softmax to get probabilities in [0, 1]:
model = NeuralNetwork(50, 3) # 50 inp, 3 out
X = torch.rand((1, 50)) # random input tensor
with torch.no_grad():
output = torch.softmax(model(X), dim=1) # softmax to convert to probabilities
print(output)
# tensor([[0.3409, 0.3107, 0.3484]]) (And now we take the highest (third number here and that is our prediction/answer)) {All these class prob sum upto 1, you can read more about softmax function its a fun trick in math which maps all numbers b/w 0-1 and they sum upto 1}
(The outputs above come from running the blocks in order after torch.manual_seed(42), with PyTorch 2.14.1 on CPU.)
How softmax formula looks like
mlp
Three things you need for any model: load the data, define the model, train it.
torchvision.datasetshas pre-packaged datasets (MNIST, CIFAR, etc). It downloads and organizes everything.DataLoaderdoes batching, shuffling and parallel loading. You loop over it during training.transforms.ToTensor()converts images to tensors and scales pixels from [0, 255] to [0.0, 1.0].
loading the dataset
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
# Define transforms: Convert to tensor and Normalize
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,)) # MNIST mean and std
])
# Download datasets
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
# Create DataLoaders
batch_size = 64
train_dataloader = DataLoader(
train_dataset,
batch_size=batch_size,
shuffle=True
)
test_dataloader = DataLoader(
test_dataset,
batch_size=batch_size,
shuffle=False
)
print(f"Training samples: {len(train_dataset)}")
print(f"Test samples: {len(test_dataset)}")
print(f"Batch size: {batch_size}")
Batch shape: (64, 1, 28, 28) = 64 images, 1 channel (grayscale), 28x28 pixels. Labels: (64,) with digits 0-9.
Every model subclasses nn.Module. Define layers in __init__, wire them in forward:
nn.Flatten(): (1, 28, 28) -> (784)nn.Linear(in, out): y = xW^T + bnn.ReLU(): max(0, x). Without it, the whole network collapses into one big linear function.
the model
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
# flatten
self.flatten = nn.Flatten()
# first linear layer transformation (first y=mx+c) : 28*28(784) -> 128
self.linear1 = nn.Linear(784, 128)
self.activation = nn.ReLU()
self.linear2 = nn.Linear(128, 64) # second layer (this MNIST model has 2 hidden layers)
self.activation = nn.ReLU()
self.linear3 = nn.Linear(64, 10) # take 64 inputs from hidden layer 2 and output the final 10 class labels
def forward(self, x):
x = self.flatten(x)
x = self.activation(self.linear1(x))
x = self.activation(self.linear2(x))
x = self.linear3(x)
return x # raw logits (no softmax here, CrossEntropyLoss handles it)
device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")
torch.manual_seed(0) # same seed, same run
model = MLP().to(device)
print(model)
'''
MLP(
(flatten): Flatten(start_dim=1, end_dim=-1)
(linear1): Linear(in_features=784, out_features=128, bias=True)
(activation): ReLU()
(linear2): Linear(in_features=128, out_features=64, bias=True)
(linear3): Linear(in_features=64, out_features=10, bias=True)
)
'''Training needs three things: a loss function, an optimizer and a training loop. The loss is nn.CrossEntropyLoss: log-softmax plus negative log-likelihood (NLL) in one (cross-entropy explained here). The optimizer is Adam, the default choice.
training loop
Five steps, every batch:
- The forward pass runs
model(batch)and returns logits. - The loss measures how wrong we are.
loss.backward()computes all gradients.optimizer.step()updates the weights.optimizer.zero_grad()resets the gradients for the next batch.
The training loop is these five steps, for every batch, for 5 epochs:
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
num_epochs = 5
for epoch in range(num_epochs):
model.train() # set to training mode
total_loss = 0.0
for x, y in train_dataloader:
x, y = x.to(device), y.to(device)
logits = model(x) # 1. forward pass
loss = loss_fn(logits, y) # 2. loss
loss.backward() # 3. gradients
optimizer.step() # 4. update the weights
optimizer.zero_grad() # 5. reset the gradients
total_loss += loss.item()
print(f"Epoch {epoch+1}/{num_epochs}, mean loss: {total_loss / len(train_dataloader):.4f}")
print("Training completed")Eval and inference:
print("Evaluation")
def evaluate(dataloader, model):
model.eval() # set to evaluation mode
correct, total = 0, 0
with torch.no_grad():
for x, y in dataloader:
x, y = x.to(device), y.to(device)
logits = model(x)
preds = logits.argmax(dim=1)
correct += (preds == y).sum().item()
total += y.size(0)
print(f"Test accuracy: {correct / total:.4f}")
evaluate(test_dataloader, model)
# --------
print("Starting inference on a sample image from test dataset")
def inference():
# sample input (test image 0 is a 7) and predict its digit and also show to verify
# set to inference/eval mode
model.eval()
with torch.no_grad():
sample_idx = 0
sample_img, sample_label = test_dataset[sample_idx]
sample_img = sample_img.to(device)
print(f"Actual label: {sample_label}")
sample_img_reshaped = sample_img.unsqueeze(0) # add batch dimension
pred_logits = model(sample_img_reshaped)
predicted_label = pred_logits.argmax(dim=1)
print(f"Predicted label: {predicted_label}")
inference()All together, the output on my M4 (PyTorch 2.14.1, MPS, seed 0):
Training samples: 60000
Test samples: 10000
Batch size: 64
Epoch 1/5, mean loss: 0.2736
Epoch 2/5, mean loss: 0.1152
Epoch 3/5, mean loss: 0.0807
Epoch 4/5, mean loss: 0.0626
Epoch 5/5, mean loss: 0.0489
Training completed
Test accuracy: 0.9691
Starting inference on a sample image from test dataset
Actual label: 7
Predicted label: tensor([7], device='mps:0')You can write the same model in a different style. Use F.relu(x) instead of an nn.ReLU() layer, and x.view(-1, 784) instead of nn.Flatten(). Swap Adam for SGD with momentum: torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9). The five steps of the loop stay the same.
doing it with raw matrices (no nn.Linear)
Same training loop, but the model defines W and b manually with nn.Parameter instead of using nn.Linear. Just to prove there's no magic.
#!/usr/bin/env python3
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
class MLP2Hidden(torch.nn.Module):
def __init__(self, h1=256, h2=128):
super().__init__()
# Manually define weights and biases
self.W1 = nn.Parameter(torch.randn(784, h1) * 0.01)
self.b1 = nn.Parameter(torch.zeros(h1))
self.W2 = nn.Parameter(torch.randn(h1, h2) * 0.01)
self.b2 = nn.Parameter(torch.zeros(h2))
self.W3 = nn.Parameter(torch.randn(h2, 10) * 0.01)
self.b3 = nn.Parameter(torch.zeros(10))
def forward(self, x):
x = x.view(-1, 784) # Flatten
# Layer 1: X @ W + b
z1 = x @ self.W1 + self.b1
h1 = F.relu(z1)
# Layer 2
z2 = h1 @ self.W2 + self.b2
h2 = F.relu(z2)
# Layer 3 (output)
logits = h2 @ self.W3 + self.b3
return logits
transform = transforms.ToTensor()
train_ds = datasets.MNIST(root="data", train=True, download=True, transform=transform)
test_ds = datasets.MNIST(root="data", train=False, download=True, transform=transform)
train_loader= DataLoader(train_ds, batch_size=128, shuffle=True)
test_loader= DataLoader(test_ds, batch_size=128)
model = MLP2Hidden()
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
num_epochs = 20
for epoch in range(num_epochs):
model.train()
total_loss = 0
for x, y in train_loader:
optimizer.zero_grad()
prediction = model(x)
loss = loss_fn(prediction, y)
loss.backward()
optimizer.step()
total_loss += loss.item()
avg_loss = total_loss / len(train_loader)
print(f"Epoch {epoch+1}, Loss: {avg_loss:.4f}")
# now prediction
def test():
model.eval()
with torch.no_grad():
x, y = next(iter(test_loader))
prediction = model(x)
print("Shape: ", prediction.shape) # [B, 10]
loss = loss_fn(prediction, y)
print("Loss: ", loss.item())
predicted_classes = torch.argmax(prediction, dim=1)
print("True labels:", y[:10].tolist())
print("Pred labels:", predicted_classes[:10].tolist())
accuracy = (predicted_classes == y).float().mean()
print("Accuracy: ", accuracy.item())
def main():
test()
main()Loss converges as we train longer:
Epoch 1, Loss: 2.3016
...
Epoch 10, Loss: 0.5778
...
Epoch 20, Loss: 0.3305
True labels: [7, 2, 1, 0, 4, 1, 4, 9, 5, 9]
Pred labels: [7, 2, 1, 0, 4, 1, 4, 9, 6, 9]backprop math for 2-hidden-layer MLP
Mapping the PyTorch code to the math, line by line:
model definition
Input:
Parameters:
forward pass
= logits (raw scores before softmax).
loss (cross-entropy)
For one sample:
where:
key gradient identity (softmax + cross entropy)
This is why you don't implement softmax in the forward pass: CrossEntropyLoss already handles it.
backpropagation
output layer (layer 3)
backprop through ReLU (layer 2)
ReLU derivative:
hidden layer 2 params
backprop through ReLU (layer 1)
hidden layer 1 params
gradient descent update
For any parameter :
= learning rate.
mapping to PyTorch code
| PyTorch Code | Mathematical Meaning |
|---|---|
x @ W + b | affine transformation |
F.relu(z) | |
CrossEntropyLoss | log-softmax + NLL |
loss.backward() | chain rule |
param.grad | |
optimizer.step() | gradient descent |
key insight
PyTorch autograd runs the exact same backprop equations above, node by node, via the chain rule.
GPU and dtypes
Float tensors default to float32, and all tensors default to the CPU. Move them to the GPU for parallelism:

x = torch.ones(16, 32)
w = torch.ones(32, 2)
y = x @ w
assert y.size() == torch.Size([16, 2]) # true
Operations happen per-example in a batch and per-token in a sequence:
x = torch.ones(4, 8, 16, 32)
w = torch.ones(32, 2)
y = x @ w
assert y.size() == torch.Size([4, 8, 16, 2])
# In this case, we iterate over values of the first 2 dimensions of x and multiply by w.recap
# y = 0.5 * (x @ w - 5)^2
# Forward pass: compute loss
x = torch.tensor([1., 2, 3])
w = torch.tensor([1., 1, 1], requires_grad=True) # Want gradient
pred_y = x @ w
loss = 0.5 * (pred_y - 5).pow(2)
# Backward pass: compute gradients
loss.backward()
assert loss.grad is None
assert pred_y.grad is None
assert x.grad is None
assert torch.equal(w.grad, torch.tensor([1., 2, 3]))