PyTorch Training Breakdown
Building Neural Networks from Scratch to Production with PyTorch
These notes cover the fundamental principles of PyTorch, from the low-level mechanics of tensors and autograd to the professional tools used in modern deep learning. The core message is that a simple five-step recipe underlies all neural network training, whether for a tiny toy model or a multi-billion-parameter LLM.
The Five-Step Training Recipe
Every neural network on Earth is trained using the same basic loop:
Forward pass – make a guess (y^)
Loss calculation – measure how wrong the guess is
Backward pass – compute gradients (blame) via
loss.backward()Parameter update – nudge parameters in the direction that reduces loss
Reset gradients – zero out gradients for the next iteration
This sequence is universal. Understanding the why behind each step removes the magic from deep learning and replaces it with clear engineering.
Tensors: The Fundamental Building Block
A tensor is PyTorch's core data structure – the "noun" of the language. It is like a NumPy multidimensional array, but with added superpowers (autograd, GPU acceleration).
Three Common Creation Patterns
Direct creation from data: Use
torch.tensor(list)to convert a Python list to a tensor.Creation from a desired shape: Use
torch.zeros(shape),torch.ones(shape), ortorch.randn(shape)when the values are unknown but the dimensions are known – common for initializing model weights.Creation by mimicking another tensor: Use
torch.randn_like(template)to create a new tensor with the same shape, dtype, and device as an existing one.
Critical Tensor Attributes
Every tensor has three essential properties:
.shape: A tuple describing the dimensions. This is the number one debugging tool – most PyTorch errors are shape mismatches..dtype: The data type of the numbers. The default istorch.float32. Model parameters must be float types to allow continuous adjustments (gradients require fractional changes)..device: Where the tensor lives –cpuorcuda(GPU).
Key rule: Model parameters (weights, biases) must be a float type (usually
float32). Data like class labels can be integers, but everything that learns must be a float.
Autograd: The Nervous System
Autograd is PyTorch's automatic differentiation engine. It is activated by the simple switch requires_grad=True. This flag tells PyTorch to track every operation performed on the tensor, building a computation graph – a live recording of calculations.
Building the Computation Graph
Consider computing z=x∗y where y=a+b.
Create parameter tensors with
requires_grad=True:a = torch.tensor(2.0, requires_grad=True) b = torch.tensor(3.0, requires_grad=True) x = torch.tensor(4.0, requires_grad=True)Perform operations:
y = a + b # creates a node "AddBackward0" z = x * y # creates a node "MulBackward0"The
grad_fnattribute points to the function that created the tensor:z.grad_fn→MulBackward0(the multiplication)y.grad_fn→AddBackward0(the addition)a.grad_fn→None(user-created, not from an operation)
When loss.backward() is later called, PyTorch walks backward through this graph to compute gradients for all parameters that have requires_grad=True.
Core Operations: Verbs of PyTorch
Elementwise vs. Matrix Multiplication
This is one of the most common beginner confusions.
*(elementwise multiplication): Multiplies matching positions. Tensors must have the same shape.@(matrix multiplication): Follows linear algebra rules. The number of columns in the first matrix must equal the number of rows in the second. This is the operation that powers neural networks.Rule: When implementing a linear layer (y^=xW+b), always use the
@operator.
Reduction Operations and the dim Argument
Reductions (sum, mean, max) collapse a tensor to fewer elements. The dim argument controls which direction to collapse.
No dim: collapse everything → single scalar.
dim=0(for 2D tensors): collapse rows → operate vertically, averaging across the row index.dim=1: collapse columns → operate horizontally, averaging across the column index.
Example with a scores tensor (2 students × 3 assignments):
scores = torch.tensor([[10,20,30],[5,10,15]])
per_assignment = scores.mean(dim=0) # each assignment averaged over students: [7.5, 15, 22.5]
per_student = scores.mean(dim=1) # each student averaged over assignments: [20, 10]Mastering dim is essential – it is used everywhere in data processing and model outputs.
Advanced Indexing: argmax and gather
torch.argmax(input, dim): Returns the index of the highest value along a given dimension. Used to get a model's predicted class.torch.gather(input, dim, index): Selects elements according to a custom "shopping list" of indices per row. Avoids slow loops.
The Forward Pass: Making a Guess
Linear Regression from Scratch
Goal: learn the relationship y=2x+1 with noise.
Setup:
n = 10 # number of data points
d_in, d_out = 1, 1
X = torch.randn(n, d_in)
true_w, true_b = torch.tensor([[2.0]]), torch.tensor([[1.0]])
y_true = X @ true_w + true_b + 0.1 * torch.randn(n, d_out) # add noise
# Initialize model parameters (the "brain")
w = torch.randn(d_in, d_out, requires_grad=True)
b = torch.randn(d_out, requires_grad=True)The forward pass (first guess):
y_hat = X @ w + bThe initial prediction is terrible (random), but autograd is already tracking the computation – notice y_hat has a grad_fn of AddBackward0.
The Loss: Quantifying the Error
For regression, the standard loss is Mean Squared Error (MSE):
Implementation:
error = y_hat - y_true
squared_error = error ** 2
loss = squared_error.mean()The loss is a single scalar – our scorecard. The goal is to make it as small as possible.
The Backward Pass: Assigning Blame
One line of code computes the gradients for all parameters:
loss.backward()After this call, the .grad attribute is populated for w and b:
w.gradcontains ∂w∂Lb.gradcontains ∂b∂L
Interpreting the gradient:
The gradient points in the direction of steepest increase of the loss.
To decrease the loss, move parameters in the opposite direction of the gradient.
A negative gradient means increasing that parameter decreases the loss; a positive gradient means decreasing it reduces the loss.
The magnitude shows the steepness.
Gradient Descent: The Update Rule
The core formula:
Where:
θ represents all parameters (w and b)
η is the learning rate – a small number (e.g., 0.01) controlling step size
∇L is the gradient of the loss
Manual update (from-scratch style):
with torch.no_grad(): # don't track these manual updates in the graph
w -= learning_rate * w.grad
b -= learning_rate * b.grad
w.grad.zero_() # reset gradients for next iteration
b.grad.zero_()Training Loop (From Scratch)
learning_rate = 0.01
epochs = 100
for epoch in range(epochs):
# 1. Forward pass
y_hat = X @ w + b
# 2. Compute loss
loss = ((y_hat - y_true) ** 2).mean()
# 3. Backward pass
loss.backward()
# 4. Update parameters
with torch.no_grad():
w -= learning_rate * w.grad
b -= learning_rate * b.grad
# 5. Zero gradients
w.grad.zero_()
b.grad.zero_()After many epochs, the loss drops, and w and b converge toward their true values (2 and 1). The model learns.
Professional PyTorch: nn.Module and nn.Linear
Managing loose tensors doesn't scale. PyTorch provides nn.Module as the standardized base plate for all models, and nn.Linear as the pre-built brick for linear (fully connected) layers.
Using nn.Linear
import torch.nn as nn
d_in, d_out = 1, 1
linear_layer = nn.Linear(in_features=d_in, out_features=d_out)
# The layer automatically creates required parameters:
# linear_layer.weight (with requires_grad=True)
# linear_layer.bias (with requires_grad=True)
y_hat = linear_layer(X) # clean forward passCreating a Custom Model with nn.Module
class LinearRegressionModel(nn.Module):
def __init__(self, in_features, out_features):
super().__init__() # crucial: call parent init
self.linear = nn.Linear(in_features, out_features)
def forward(self, x):
return self.linear(x)
model = LinearRegressionModel(in_features=1, out_features=1)
print(model) # prints the architectureAll parameters are now neatly organized under model.parameters().
Activation Functions: Adding Nonlinearity
Without nonlinearities, stacking linear layers is equivalent to a single linear layer. Activation functions introduce kinks, allowing the network to learn complex patterns.
nn.ReLU: ReLU(x)=max(0,x). Sets negative inputs to zero. Simple and effective.nn.GELU: A smooth, gently curving version of ReLU. The modern standard for transformers (GPT, LLaMA).nn.Softmax: Converts raw scores (logits) into a probability distribution (all values in [0,1], sum to 1). Almost always used on the final layer for classification.
relu = nn.ReLU()
# Input: [-2, -0.5, 0.5, 2] → Output: [0, 0, 0.5, 2]
gelu = nn.GELU()
# Same input, but negative values are gently squashed, not snapped to zero.
softmax = nn.Softmax(dim=-1)
logits = torch.tensor([[1.0, 2.0, 3.0]])
probs = softmax(logits) # [[0.0900, 0.2447, 0.6653]]Essential Building Blocks for Modern Architectures
nn.Embedding
Turns discrete tokens (word IDs) into dense continuous vectors. A learnable lookup table.
vocab_size = 10
embedding_dim = 3
embedding_layer = nn.Embedding(vocab_size, embedding_dim)
input_ids = torch.tensor([[1, 5, 0, 8]]) # shape: (1,4)
embeddings = embedding_layer(input_ids) # shape: (1,4,3)nn.LayerNorm
Stabilizes training by rescaling activations to have zero mean and unit variance. Essential for deep networks.
norm = nn.LayerNorm(normalized_shape=3)
input_features = torch.randn(2, 3)
normalized = norm(input_features) # each feature vector has mean~0, std~1nn.Dropout
Prevents overfitting by randomly zeroing out a fraction of neurons during training. Only active in train mode.
dropout = nn.Dropout(p=0.5)
dropout.train() # during training: randomly zeroed
dropout.eval() # during evaluation: identity pass (no dropout)This on/off switch is a cornerstone of regularization.
Optimizer: Automating Parameter Updates
Instead of manually updating each parameter, use torch.optim. The most common optimizer is Adam.
import torch.optim as optim
learning_rate = 0.01
optimizer = optim.Adam(model.parameters(), lr=learning_rate)The Professional Training Loop: Three-Line Mantra
for epoch in range(epochs):
# Forward pass
y_hat = model(X)
# Loss calculation
loss = loss_fn(y_hat, y_true) # e.g., nn.MSELoss()
# Three-line mantra (replaces manual steps 3-5)
optimizer.zero_grad() # reset gradients
loss.backward() # compute gradients
optimizer.step() # update parameters using the gradientThis clean pattern is universal in 99% of PyTorch code.
Bridging to Large Language Models
The toy linear regression model and a massive LLM (e.g., LLaMA 38B) are trained with exactly the same five-step logic. The only differences are scale and architecture.
Feed-Forward Network Inside a Transformer
Inside every transformer block, there is a small subcomponent called a feed-forward network (FFN):
class FeedForwardNetwork(nn.Module):
def __init__(self, d_model, d_ff):
super().__init__()
self.layer1 = nn.Linear(d_model, d_ff)
self.activation = nn.GELU()
self.layer2 = nn.Linear(d_ff, d_model)
def forward(self, x):
return self.layer2(self.activation(self.layer1(x)))This is the same nn.Linear brick you learned, stacked with an activation.
Scale Comparison
Feature | Toy Model | LLM (e.g., LLaMA 38B) |
|---|---|---|
Model type | Linear Regression | Transformer |
Layer type |
|
|
Weight matrix shape | 1×1 | 4,096 × 14,336 (58 million values) |
Operation | XW | XW (same! just larger) |
Total parameters | 2 | ~8 billion |
Loss function | MSE | Cross-Entropy (for next-word prediction) |
Training loop |
| Identical |
The process is the same. Autograd does not care how many parameters there are. The optimizer manages them all.
Summary: The Engine Demystified
A model is an
nn.Modulecontaining layers.A layer is a container for parameters that performs a mathematical operation.
Learning is just repeatedly updating those parameters using the three-line mantra:
optimizer.zero_grad(),loss.backward(),optimizer.step().The magic of deep learning is replaced by solid engineering – a universal recipe that scales from two parameters to billions.

Ask anything
We've read this whole study set, so questions about it get the best answers.