3 min read

PyTorch

The most useful way to approach PyTorch is as a complete modeling workflow. This article connects tensors and data loading to training, evaluation, experiment tracking, and deployment, with the examples and diagrams kept alongside the concepts they explain.

Python building blocks

https://www.pythoncheatsheet.org/

Python building blocks — illustration
Python building blocks — illustration
Python building blocks — illustration
Python building blocks — illustration

Python exceptions

There are 150+ exception types

a. How to raise exception

Pytorch — Exceptions

b. Exception handling block

Pytorch — Exceptions

c. Create Custom exceptions

Pytorch — Exceptions

Getting started with PyTorch

Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Getting started with PyTorch — illustration
Pytorch — Intro
Getting started with PyTorch — illustration

Tensors and fundamentals

https://www.learnpytorch.io/00_pytorch_fundamentals/

Pytorch — Fundamentals
Tensors and fundamentals — illustration
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Tensors and fundamentals — illustration
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Tensors and fundamentals — illustration
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Tensors and fundamentals — illustration
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Pytorch — Fundamentals
Tensors and fundamentals — illustration
Tensors and fundamentals — illustration

Datasets, data loaders, and batches

With the basic operations in place, the next step is getting data into the training loop in a usable form.

DataLoaders and Datasets

Pytorch provides two classes for data loading and processing

Dataset class: Stores or fetches data

DataLoader class: Loads and batches data

Dataset Class

Contains all data for training, validation, testing

Stores data directly in an attribute or retrieves data from cloud storage

__len__(): returns the number of samples in dataset

__getitem__(index): returns the sample at specific index

DataLoader Class

Feeds data from Dataset to model in efficient way

Collects multiple samples together into batches

Shuffles data for each epoch

Utilizes multiple works to call _getitem__ for different indices to retrieve data

Data from workers is placed into staging area to form batches

Internal Collate function is used to convert individual samples into a batch

Data undergoes transformations before being fed to the model

Transformations can occur on individual samples as they are fetched

At the start of each epoch

New set of Batches are created from shuffled dataset

Each batch is processed individually

Code
train_data = datasets.FashionMNIST(
Code
root="data",

So we downloaded the whole dataset

Code
train=True,
Code
download=True,
Code
transform=transform,
Code
)
Code
test_data = datasets.FashionMNIST(
Code
root="data",
Code
train=False,
Code
download=True,
Code
transform=transform,
Code
train_dataloader = DataLoader(train_data, batch_size=64, shuffle=True)
Code
)
Code
test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)
Code
len(train_dataloader)

938

Code
for a, b in train_dataloader:
Code
print(a.shape, b.shape)
Code
torch.Size([64, 1, 28, 28]) torch.Size([64])
Code
torch.Size([64, 1, 28, 28]) torch.Size([64])
Code
torch.Size([64, 1, 28, 28]) torch.Size([64])
Code
torch.Size([64, 1, 28, 28]) torch.Size([64])

Each batch is 64 images [a], 64 labels [b]

Code
. . .
Datasets, data loaders, and batches — illustration
Code
class M1_Traditional:
Code
def __init__(self, input, hidden, output):
Code
self.weights1 = torch.randn(input, hidden, requires_grad=True) * 0.01
Code
self.bias1 = torch.zeros(hidden, requires_grad=True)
Code
self.weights2 = torch.randn(hidden, output, requires_grad=True) * 0.01
Code
self.bias2 = torch.zeros(output, requires_grad=True)
Code
def forward(self, x):
Code
x = x.view(x.size(0), -1)
Code
x = torch.matmul(x, self.weights1) + self.bias1

Hota kuch yun tha, but ab abstraction hogai he

Code
x = F.relu(x)
Code
x = torch.matmul(x, self.weights2) + self.bias2
Code
from torch import nn
Code
x = F.relu(x)
Code
class M1(nn.Module):

Basically each tensor has a gradient class_attribute

Code
return x
Code
def __init__(self, input, hidden, output):

The gradient attribute stores partial derivatives of loss function with respect to that parameter

Code
super().__init__()
Code
self.layers = nn.Sequential(
Code
nn.Flatten(),

Tou agar ek parameter he

Code
nn.Linear(input, hidden),

Tou uska .grad value hogi

Code
nn.ReLU(),

​L is the scalar loss

Code
nn.Linear(hidden, output),
Code
nn.ReLU()
Code
)
Code
def forward(self, x):
Code
model = M1(28*28, 28*28, 10).to(device)
Code
return self.layers(x)
Code
from torch import optim
Code
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
Code
lossfn = nn.CrossEntropyLoss()
Datasets, data loaders, and batches — illustration

Loss even though is a tensor, but is a special leaf tensor

See the value?

Pytorch will be able to perform backpropagation from it because the loss tensor stores the computational graph

Autograd tracks all operations applied to tensors with requires_grad=true during forward pass, when .backward() is called, It computes the gradients based on chain rule by traversing computational graph in reverse order

A regression workflow

https://www.learnpytorch.io/01_pytorch_workflow/

A regression workflow — illustration
Pytorch — Regression Workflow
Pytorch — Regression Workflow
A regression workflow — illustration
A regression workflow — illustration
A regression workflow — illustration
A regression workflow — illustration
Pytorch — Regression Workflow
Pytorch — Regression Workflow
Pytorch — Regression Workflow
A regression workflow — illustration

A classification workflow

https://www.learnpytorch.io/02_pytorch_classification/

A classification workflow — illustration
A classification workflow — illustration
A classification workflow — illustration
A classification workflow — illustration
A classification workflow — illustration
A classification workflow — illustration
A classification workflow — illustration
A classification workflow — illustration

Computer vision

Computer vision — illustration

https://poloclub.github.io/cnn-explainer/

Computer vision — illustration
Pytorch — Computer vision
Pytorch — Computer vision
Computer vision — illustration
Computer vision — illustration
Pytorch — Computer vision
Computer vision — illustration
Computer vision — illustration
Pytorch — Computer vision
Pytorch — Computer vision
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration
Computer vision — illustration

Working with custom datasets

https://paperswithcode.com/sota

https://huggingface.co/models

Working with custom datasets — illustration
Pytorch — Custom datasets
Working with custom datasets — illustration
Pytorch — Custom datasets
Working with custom datasets — illustration
Pytorch — Custom datasets
Pytorch — Custom datasets
Working with custom datasets — illustration
Working with custom datasets — illustration
Working with custom datasets — illustration
Pytorch — Custom datasets
Pytorch — Custom datasets
Working with custom datasets — illustration
Pytorch — Custom datasets
Pytorch — Custom datasets
Working with custom datasets — illustration
Pytorch — Custom datasets
Working with custom datasets — illustration
Pytorch — Custom datasets
Working with custom datasets — illustration
Working with custom datasets — illustration
Pytorch — Custom datasets
Working with custom datasets — illustration
Working with custom datasets — illustration
Working with custom datasets — illustration
Working with custom datasets — illustration
Working with custom datasets — illustration
Pytorch — Custom datasets
Pytorch — Custom datasets
Pytorch — Custom datasets
Working with custom datasets — illustration
Working with custom datasets — illustration
Working with custom datasets — illustration
Pytorch — Custom datasets
Pytorch — Custom datasets
Pytorch — Custom datasets
Pytorch — Custom datasets
Pytorch — Custom datasets
Pytorch — Custom datasets
Pytorch — Custom datasets
Pytorch — Custom datasets
Pytorch — Custom datasets
Pytorch — Custom datasets
Pytorch — Custom datasets
Working with custom datasets — illustration
Working with custom datasets — illustration
Working with custom datasets — illustration
Working with custom datasets — illustration

Organizing training code

https://www.learnpytorch.io/05_pytorch_going_modular/

Pytorch — Going Modular
Pytorch — Going Modular
Organizing training code — illustration
Organizing training code — illustration

Transfer learning

https://www.learnpytorch.io/06_pytorch_transfer_learning/

Transfer learning — illustration
Pytorch — Transfer Learning
Pytorch — Transfer Learning
Pytorch — Transfer Learning
Transfer learning — illustration
Transfer learning — illustration
Transfer learning — illustration
Transfer learning — illustration
Transfer learning — illustration

Tracking experiments

Tracking experiments — illustration
Pytorch — MLFlow

Reproducing a paper

https://www.learnpytorch.io/08_pytorch_paper_replicating/

Pytorch — Paper replication
Reproducing a paper — illustration
Pytorch — Paper replication
Reproducing a paper — illustration
Pytorch — Paper replication
Pytorch — Paper replication
Reproducing a paper — illustration
Reproducing a paper — illustration
Reproducing a paper — illustration

Deploying a model

The workflow ends with using the trained model outside the training process.

https://www.learnpytorch.io/09_pytorch_model_deployment/

Deploying a model — illustration
Pytorch — Deployment
Deploying a model — illustration
Deploying a model — illustration
Pytorch — Deployment
Deploying a model — illustration
Deploying a model — illustration
Pytorch — Deployment
Pytorch — Deployment
Pytorch — Deployment
Pytorch — Deployment
Pytorch — Deployment
Deploying a model — illustration
Deploying a model — illustration

If you set the parameter share=True in the launch() method, Gradio also provides you with a shareable link such as https://123XYZ.gradio.app (this link is an example only and likely expired) which is valid for 72-hours.

From <https://www.learnpytorch.io/09_pytorch_model_deployment/#35-saving-effnetb2-feature-extractor>

Pytorch — Deployment
Deploying a model — illustration
Deploying a model — illustration
Pytorch — Deployment
Pytorch — Deployment
Pytorch — Deployment
Pytorch — Deployment
Deploying a model — illustration
Pytorch — Deployment
Deploying a model — illustration
Deploying a model — illustration