Deep Learning with PyTorch — Foundations and Training Loops
Author: Bidhya Yadav
Focus: Understanding Deep Learning Mechanics from First Principles
1. Big Picture
Modern deep learning is fundamentally:
PyTorch provides the framework for:
- tensor computation
- automatic differentiation
- neural network construction
- optimization
- GPU acceleration
2. Core Learning Goal
The objective is NOT merely learning APIs.
The objective is to understand:
Specifically:
- tensor transformations
- gradients
- backpropagation
- optimization
- training loops
- parameter updates
3. Tensors
What Is a Tensor?
A tensor is:
Examples:
Scalar (0D)
Vector (1D)
Shape:
Matrix (2D)
Shape:
Higher-Dimensional Tensor
Example image batch:
Example:
Meaning:
- batch size = 32
- RGB channels = 3
- image size = 224×224
4. Tensor Creation in PyTorch
Create Tensor
Random Tensor
Meaning:
5. Tensor Shapes
Tensor shape debugging is one of the most important practical skills.
Example:
A large fraction of deep learning debugging involves:
6. Tensor Operations
Deep learning is fundamentally repeated tensor transformations.
Addition
Matrix Multiplication
Output shape:
This operation is central to neural networks.
7. Neural Networks as Tensor Transformations
A neural network layer is essentially:
Where:
x= input tensorW= weight matrixb= bias vectory= output tensor
This is fundamentally:
8. Learnable Parameters
Parameters are:
Example:
Training adjusts these parameters to reduce error.
9. Autograd — PyTorch's Core Superpower
PyTorch automatically computes gradients.
Example:
PyTorch internally builds a computational graph.
10. Computational Graph
flowchart LR
A[x] --> B[y = x²]
Calling:
computes:
Result:
Output:
because:
11. What Gradients Mean
A gradient tells us:
Without gradients:
- no learning
- no backpropagation
- no deep learning
12. The Big Deep Learning Cycle
flowchart LR
A[Input Tensor] --> B[Neural Network]
B --> C[Predictions]
C --> D[Loss Function]
D --> E[Gradients]
E --> F[Parameter Updates]
F --> B
13. PyTorch Neural Networks — nn.Module
PyTorch neural networks are built using:
Think of nn.Module as:
It provides:
- parameter tracking
- GPU support
- gradient integration
- model saving/loading
- train/eval switching
14. Basic Neural Network Example
import torch
import torch.nn as nn
class SimpleNet(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(4, 8)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(8, 2)
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
15. Understanding __init__()
is the constructor.
It runs automatically when creating the model:
This is where layers are defined.
16. Understanding self
Example:
means:
Without self, the layer would disappear after initialization.
17. Understanding super().__init__()
This line is extremely important:
Meaning:
This initializes PyTorch internal machinery:
- parameter registration
- gradient tracking
- state handling
- module bookkeeping
Without this, many PyTorch features break.
18. Forward Pass
defines:
This is the actual neural computation.
19. Neural Network Flow
flowchart LR
A[Input] --> B[Linear Layer]
B --> C[ReLU Activation]
C --> D[Linear Layer]
D --> E[Output Logits]
20. Why Activations Matter
Without activations:
collapses into:
Nonlinear activations like ReLU give neural networks expressive power.
21. ReLU
Most common activation function:
PyTorch:
22. Logits
Neural networks usually output:
These are:
Example:
Not probabilities yet.
23. Softmax
Converts logits into probabilities.
Output probabilities sum to 1.
24. Loss Functions
Loss measures:
Training tries to minimize loss.
25. Cross Entropy Loss
Very common for classification.
Usage:
Important:
PyTorch handles this internally.
26. Optimizers
Optimizers update parameters using gradients.
Example:
Conceptually:
27. The Full Training Loop
This is the heart of practical deep learning.
for epoch in range(num_epochs):
for inputs, targets in dataloader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
28. Training Loop Visualization
flowchart LR
A[Input Batch] --> B[Forward Pass]
B --> C[Predictions]
C --> D[Loss Computation]
D --> E[Backward Pass]
E --> F[Gradient Computation]
F --> G[Optimizer Update]
G --> H[Updated Parameters]
H --> B
29. Step-by-Step Explanation
Step 1 — Forward Pass
Model computes predictions.
Step 2 — Compute Loss
Measure prediction error.
Step 3 — Clear Old Gradients
PyTorch accumulates gradients by default. Old gradients must be cleared.
Step 4 — Backpropagation
PyTorch computes gradients for all parameters.
Step 5 — Parameter Update
Optimizer updates weights using gradients.
30. Epochs
One epoch means:
Example:
One epoch:
31. Batches
Training usually uses mini-batches.
Example:
Meaning:
Benefits:
- efficient GPU computation
- lower memory usage
- faster optimization
32. DataLoader
PyTorch automates batching using:
Example:
from torch.utils.data import TensorDataset, DataLoader
dataset = TensorDataset(X, y)
dataloader = DataLoader(
dataset,
batch_size=16,
shuffle=True
)
33. Why Shuffle Data?
helps avoid:
- ordering bias
- repetitive gradient patterns
- poor convergence
34. Training vs Inference
Very important distinction.
Training Mode
Enables:
- dropout
- batchnorm updates
- gradient behavior for training
Evaluation Mode
Disables:
- dropout randomness
- batchnorm updates
Used for inference and validation.
35. torch.no_grad()
Inference often uses:
Benefits:
- lower memory usage
- faster inference
- no gradient tracking
36. Common Beginner Mistakes
Forgetting zero_grad()
Causes incorrect gradient accumulation.
Applying Softmax Before CrossEntropyLoss
Usually incorrect.
Forgetting model.eval()
Causes inconsistent inference behavior.
Tensor Shape Mismatches
Extremely common.
Always inspect:
37. Deep Mental Model
Deep learning training is fundamentally:
Everything else is refinement and engineering.
38. Final Conceptual Summary
Tensors
Represent multidimensional numerical data.
Neural Networks
Parameterized tensor transformation systems.
Forward Pass
Computes predictions.
Loss Function
Measures prediction error.
Backpropagation
Computes gradients.
Optimizer
Updates parameters.
Training Loop
Repeated optimization cycle over data batches.
39. Why Multiple Epochs Help
The dataset stays the same, but the model parameters change after every batch update.
So each epoch trains a slightly improved version of the model.
Training is gradual:
Each epoch produces new gradients because the model itself has changed.
Mini-batches also provide noisy gradient estimates, so repeated passes help stabilize and refine learning.
Too many epochs can eventually cause overfitting:
Final intuition:
Each epoch revisits the same data using improved parameters,
allowing the model to progressively refine its representations.
40. Recommended Next Topics
Natural next steps:
- Backpropagation and chain rule intuition
- Optimization algorithms (SGD vs Adam)
- Vanishing/exploding gradients
- Regularization
- CNNs
- Transformers
- Attention mechanisms
- Transfer learning
- Fine-tuning
- Distributed training