![Revisit consent button](../images/body-df29beacd7496220cc94.svg)
We value your privacy
We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies.
Customise Reject All Accept All
Customise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)
We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.
The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more
NecessaryAlways Active
Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.
  * Cookie
BCTempID
  * Duration
10 minutes
  * Description
No description available.


  * Cookie
__cf_bm
  * Duration
1 hour
  * Description
This cookie, set by Cloudflare, is used to support Cloudflare Bot Management. 


  * Cookie
AWSALBCORS
  * Duration
7 days
  * Description
Amazon Web Services set this cookie for load balancing.


  * Cookie
_cfuvid
  * Duration
session
  * Description
Cloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services


  * Cookie
li_gc
  * Duration
6 months
  * Description
Linkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.


  * Cookie
__hssrc
  * Duration
session
  * Description
This cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.


  * Cookie
__hssc
  * Duration
1 hour
  * Description
HubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.


  * Cookie
wpEmojiSettingsSupports
  * Duration
session
  * Description
WordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.


  * Cookie
BCSessionID
  * Duration
1 year 1 month 4 days
  * Description
Blueconic sets this cookie as a unique identifier for the BlueConic profile.


  * Cookie
_octo
  * Duration
1 year
  * Description
No description available.


  * Cookie
logged_in
  * Duration
1 year
  * Description
No description available.


  * Cookie
__Secure-YEC
  * Duration
past
  * Description
YouTube sets this cookie to stores the user's video player preferences using embedded YouTube video


  * Cookie
__eoi
  * Duration
6 months
  * Description
Description is currently not available.


  * Cookie
AWSALBTGCORS
  * Duration
7 days
  * Description
No description available.


  * Cookie
login-status-p
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
AWSALBTG
  * Duration
7 days
  * Description
No description available.


  * Cookie
csrf_token
  * Duration
session
  * Description
No description available.


  * Cookie
token_v2
  * Duration
1 day
  * Description
Description is currently not available.


  * Cookie
D
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
PHPSESSID
  * Duration
session
  * Description
This cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.


  * Cookie
VISITOR_PRIVACY_METADATA
  * Duration
6 months
  * Description
YouTube sets this cookie to store the user's cookie consent state for the current domain. 


  * Cookie
cookietest
  * Duration
session
  * Description
The cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.


  * Cookie
__Host-airtable-session
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
__Host-airtable-session.sig
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
m
  * Duration
1 year 1 month 4 days
  * Description
Stripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.


  * Cookie
BIGipServer*
  * Duration
session
  * Description
Marketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. 


  * Cookie
__cfruid
  * Duration
session
  * Description
Cloudflare sets this cookie to identify trusted web traffic.


  * Cookie
_GRECAPTCHA
  * Duration
6 months
  * Description
Google Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.


  * Cookie
__Secure-YNID
  * Duration
6 months
  * Description
Google cookie used to protect user security and prevent fraud, especially during the login process.


  * Cookie
cookieyes-consent
  * Duration
1 year
  * Description
CookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.


Functional
Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.
  * Cookie
lidc
  * Duration
1 day
  * Description
LinkedIn sets the lidc cookie to facilitate data center selection.


  * Cookie
brw
  * Duration
1 year
  * Description
No description available.


  * Cookie
brwConsent
  * Duration
5 minutes
  * Description
Description is currently not available.


  * Cookie
WMF-Uniq
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
loom_anon_comment
  * Duration
1 year
  * Description
No description available.


  * Cookie
loom_referral_video
  * Duration
session
  * Description
Description is currently not available.


  * Cookie
VISITOR_INFO1_LIVE
  * Duration
6 months
  * Description
A cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.


  * Cookie
yt-remote-connected-devices
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
ytidb::LAST_RESULT_ENTRY_KEY
  * Duration
Never Expires
  * Description
The cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.


  * Cookie
yt-remote-device-id
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
yt-remote-session-name
  * Duration
session
  * Description
The yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.


  * Cookie
yt-remote-fast-check-period
  * Duration
session
  * Description
The yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.


  * Cookie
yt-remote-session-app
  * Duration
session
  * Description
The yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.


  * Cookie
yt-remote-cast-available
  * Duration
session
  * Description
The yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.


  * Cookie
yt-remote-cast-installed
  * Duration
session
  * Description
The yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.


  * Cookie
cp_session
  * Duration
3 months
  * Description
Codepen sets this cookie for Help systems found in the website.


  * Cookie
loid
  * Duration
1 year 1 month 4 days
  * Description
This cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.


Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.
  * Cookie
__hstc
  * Duration
6 months
  * Description
Hubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).


  * Cookie
hubspotutk
  * Duration
6 months
  * Description
HubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.


  * Cookie
_ga
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.


  * Cookie
_ga_*
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to store and count page views.


  * Cookie
__Host-psifi.analyticsTrace
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
__Host-psifi.analyticsTraceV2
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
_gh_sess
  * Duration
session
  * Description
GitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.


  * Cookie
YSC
  * Duration
session
  * Description
YSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.


  * Cookie
ajs_anonymous_id
  * Duration
1 year
  * Description
This cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.


  * Cookie
vuid
  * Duration
1 year 1 month 4 days
  * Description
Vimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. 


Performance
Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.
  * Cookie
AWSALB
  * Duration
7 days
  * Description
AWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.


  * Cookie
acq
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
acq.sig
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
ptc
  * Duration
2 years
  * Description
No description available.


Advertisement
Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.
  * Cookie
muc_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to collect user behaviour and interaction data to optimize the website.


  * Cookie
guest_id_marketing
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
guest_id_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
personalization_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.


  * Cookie
guest_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.


  * Cookie
bcookie
  * Duration
1 year
  * Description
LinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.


  * Cookie
__Secure-ROLLOUT_TOKEN
  * Duration
6 months
  * Description
YouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.


  * Cookie
yt.innertube::nextId
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
yt.innertube::requests
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
session_tracker
  * Duration
session
  * Description
This cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.


  * Cookie
edgebucket
  * Duration
session
  * Description
Reddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.


  * Cookie
did
  * Duration
1 year
  * Description
Arbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.


Uncategorised
Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet.
No cookies to display.
Reject All Save My Preferences Accept All
Toggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation
[](https://towardsdatascience.com/)
Publish AI, ML & data-science insights to a global community of data professionals.
Sign in[Submit an Article](https://write.insightmediagroup.io)
[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)
* * *
[Write For TDS](https://towardsdatascience.com/submissions/)
[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search
[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)
# PyTorch Explained: From Automatic Differentiation to Training Custom Neural Networks
The core mechanics of Deep Learning, and how to think the PyTorch way.
[Avishek Biswas](https://towardsdatascience.com/author/neural.avb/)
September 24, 202513 min read
![](../images/000.png)
Let's learn PyTorch!
Deep learning is shaping our world as we speak. In fact, it has been slowly revolutionizing software since the early 2010s. In 2025, PyTorch is at the forefront of this revolution, emerging as one of the most important libraries to train neural networks.
Whether you are working with computer vision, building large language models (LLMs), training a reinforcement learning agent, or experimenting with graph neural networks - your path is going to cross through PyTorch once you enter deep learning city.
_All images provided in this article have been produced by the author._
This guide will provide a whirlwind tour of PyTorch's methodologies and design principles. Over the next hour, we're going to cut through the noise and get straight to the heart of how neural networks are actually trained.
> This article is about PyTorch's foundational concepts and _how_ to compose and train models — **from simple linear regression all the way to a modern transformer block**.
> More importantly than the specific code examples presented here, the goal of this article is to teach the main ideas, project-level architectures, and abstractions to work with PyTorch.
> **In other words, how to think "the PyTorch way".**
Before we get that far, it is important to understand the basics. PyTorch is built on two core abstractions: tensors and automatic differentiation. Master these two — how tensors store data, and how gradients are used to train neural networks — and the rest of PyTorch will feel natural. Let's discuss Tensors first.
Learn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.
## 1. Basics of Tensors
A tensor is a **multidimensional array** with a dtype, a device, and optional gradient tracking. If you know NumPy arrays, think of tensors as numpy arrays with a few major benefits:
  * **GPU utilization** : Tensors can perform massively parallel operations in the GPU. Matrix multiplications, additions, and even conditional statements are all supported.
  * **Computation Graph:** Instead of imagining tensors as an isolated block of data, think of it as a node on a computation graph. (Shown below)
  * **Automatic Differentiation:** PyTorch automatically calculates partial derivatives of each differentiable operation it performs. We will discuss what this actually means, and why this is a huge deal for training neural networks very shortly.


![](../images/001.png)
A simple computation graph. Pytorch doesn't just calculate the output, but it also stores information about what nodes the data flows through to generate the output. (Source: Author)
## 2. Automatic Differentiation (Autograd)
Neural networks in PyTorch construct a dynamic computation graph, and use it to compute gradients automatically. Let's see a simple example to learn this.
Let us begin with a clean, scalar example so that shapes and values are easy to reason about. The following code computes `z = x^2 + y^3` for scalar x and y, then calls backward to obtain `dz/dx` and `dz/dy`. 
python

```
x = torch.tensor(2.0, requires_grad=True)
y = torch.tensor(3.0, requires_grad=True)

# Forward pass: compute z = x^2 + y^3
z = x**2 + y**3

# Backward pass: compute gradients
z.backward()
dz_dx = x.grad # partial derivative wrt x
dz_dy = y.grad # partial derivative wrt y
```

What is happening:
  * We created two tensors `x` and `y` with `requires_grad=True`. This tells autograd to track their operations.
  * The forward computation constructs a small graph for z.
  * `z.backward()` triggers the reverse-mode autodiff: PyTorch computes the gradients and places them in `x.grad` and `y.grad`.


Here is what the results of the above block of code will look like:
![](../images/body-f5595a7760d68487956c.png)
If you did some mental math, here's what the partial derivatives look like for that equation when calculated analytically (spoiler: it works!):
![](../images/body-9c0333c589987fc2dece.png)
Analytical Solution (Source: Author)
### Chain Rule
[Chain Rule](https://en.wikipedia.org/wiki/Chain_rule) in calculus is a fundamental formula for differentiating composite functions, which are essentially functions within other functions. In simpler terms, you work from the outside in, taking the derivative of each "layer" of the function and multiplying them together.
Let's take a simple example of how the chain rule works in PyTorch. Let's say you have the following three-step equation:
Eqn 1: `y = x^2`  
Eqn 2: `z = y + 1`  
Eqn 3: `w = z^2`
Basically, `w` depends on `z`, `z` depends on `y`, `y` depends on `x`. _A basic chain of compositionality._ And let's say you want to find the derivative of `w` with respect to `x`
The chain rule in calculus states that to find `dw/dx` we calculate the gradients up the chain of dependencies and multiply them. So:  
`dw/dx = dw/dz * dz/dy * dy/dx`  
  
Let's see how PyTorch does this:
python

```
# requires_grad=True tells PyTorch to compute the gradients for this tensor
x = torch.tensor(2.0, requires_grad=True)

# Define the forward pass
y = x**2 
z = y + 1
w = z**2

# Calculate the gradient
w.backward()

# print the gradient
print(x.grad) # 40
```

And that's it! _It just works_. 
What's even more special is that instead of defining x as a scalar like we did above, we can also define it as a multi-dimensional tensor.  
  
Here's what happens when we change the first line from initializing a scalar with `torch.tensor(2)` to a 1D-tensor with `torch.tensor([-1, 2])`
![](../images/body-95a69d211635f5a181a1.png)
Notice how when x is a vector, Pytorch calculates the gradients for each element of x
This is what makes PyTorch _so_ _cool_. You can simultaneously (or parallely) compute gradients for multiple elements _just like that_.
When working on deep learning projects, our inputs are generally multi-dimensional, so PyTorch does a lot of heavy lifting in the background by parallelizing the gradient computation!
### The Pytorch formula
As seen in the previous example, the PyTorch game plan is pretty simple.
  1. Define the "forward pass" of your equation, i.e., how is your _dependent_ variable derived from your _independent_ variables?
  2. PyTorch automatically computes the backward propagation (provided your equations are differentiable)


![](../images/body-b79575a13f590a3fa12b.jpeg)
We define the forward function of the computation graph. PyTorch automatically computes the gradients. (Source: Author)
## 3. Training models
Now that we understand the basics of auto differentiation, let's see how [linear regression](https://en.wikipedia.org/wiki/Linear_regression) works in PyTorch. The code below constructs a small housing-style dataset with two features (area and age), normalizes them to the range of [-1, 1], and prepares us for some good old-fashioned linear regression.
python

```
df = pd.DataFrame(
    {
        "area": [120, 180, 150, 210, 105],
        "age": [5, 2, 1, 2, 1],
        "price": [30, 90, 100, 180, 85]
    }
)
df = normalize(df)
```

To do anything with PyTorch, we must first transfer the data into tensors! Notice how the data tensors X and Y do not require gradients because they are constants (i.e., they don't change during training).
The weights `W` and `B` are trainable, though. We will update them to _fit_ our dataset. To make it trainable through backpropagation, we need to set `requires_grad=True` for these declarations.
Look at the code below:
python

```
# Note that these are constants, we are not going to update them
X = torch.tensor(df[["area", "age"]].values, dtype=torch.float32)
Y = torch.tensor(df[["price"]].values, dtype=torch.float32)

# These "require_grad" So they are trainable weights.
W = torch.rand(size=(2, 1), requires_grad=True)
B = torch.rand(1, requires_grad=True)
```

Next, let's generate a prediction! The forward pass uses the idiomatic matrix multiplication and addition, i.e. `X @ W + B`. 
python

```
# Generate a prediction
pred = X @ W + B
```

The `@` operator basically does matrix multiplication between X and W. The `X @ W + B` model performs a "[linear transformation](https://en.wikipedia.org/wiki/Linear_map)" of X. Our goal is to tune the trainable weights W and B so that the prediction is closer to our target ground truth.
Next, we calculate the error as the mean square error loss. It calculates the distance between our current prediction and the ground truth. If we call `loss.backward()` we will also get the gradients of the trainable variables in the graph (i.e., W and B).
python

```
loss.backward()
dW = W.grad # Tells us "how much W must change to reduce the loss"
dB = B.grad # and "how much B must change to reduce the loss"

```

`dW` and `dB` are the gradients of W and B with respect to the loss function. We can apply "[gradient descent](https://en.wikipedia.org/wiki/Gradient_descent)" to nudge these trainable parameters in the direction indicated by the gradient.
python

```
lr = 0.2 # Learning rate: tells us how much we should update the weights
with torch.no_grad():
    W = W - lr * dW # Updating W with Gradient descent
    B = B - lr * dB # Updating B with Gradient descent

```

Understanding linear regression, loss calculation, and gradient descent are some of the pillars of machine learning, and by extension, deep learning. While updating the weights manually by subtracting the gradients is possible, it is infeasible in practice for deep neural networks with multiple layers of weights. If only there had been a way to automatically update weights without worrying about keeping track like this!
**Side note**  
The above technique of taking small steps in the optimization space to iteratively learn the weights is called Gradient Descent. _Note that there are better ways to learn the optimal W and B for small datasets. Like the_ _**Normal equation**_ _, which gives us an analytical solution that doesn't require any steps or iteration. It is however, computationally expensive for large datasets. For large matrices, the standard approach is to divide the data into minibatches and apply gradient descent individually. This technique is known as_[ _Stochastic Gradient Descent_](https://en.wikipedia.org/wiki/Stochastic_gradient_descent) _(SGD)._
### Optimizers
PyTorch optimizers are algorithms (like SGD, Adam, or RMSprop) that adjust the model's weights and biases based on the computed gradients to minimize the loss function.
Let's check how the above Linear Regression code will look if we replaced the manual weight updates with PyTorch optimizers.
python

```
from torch.optim import SGD
... 

W = torch.rand(size=(2, 1), requires_grad=True)
B = torch.rand(1, requires_grad=True)
optimizer = SGD(params = [W, B], lr=0.1)
for step in range(10):
    pred = X @ W + B # Forward pass
    loss = ((Y - pred) ** 2).mean() # Calculate loss
    loss.backward() # Calculate gradients
    optimizer.step() # Update W and B according to gradients
    optimizer.zero_grad() # Reset all gradients
```

The core loop for training models in PyTorch looks like this:
  * Forward pass to compute `pred `
  * Calculate`loss` by finding the error between the prediction (pred) and the ground truth (Y)
  * Backward pass with `loss.backward()` to populate `W.grad` and `B.grad.`
  * Step with `optimizer.step()` to update parameters.
  * Zero gradients with `optimizer.zero_grad()` to avoid accumulation.


SGD is a solid baseline for linear regression. As you scale up or face noisier gradients, adaptive optimizers can help. This is where PyTorch's suite of open source optimizers comes into play. This includes adaptive optimizers, like Adam, that use techniques such as momentum and per-parameter learning rates to achieve faster and more stable convergence on these challenging tasks. Here is a flashcard comparing various popular ones:
![](../images/body-383b8e79ed641a1513e8.png)
Some common PyTorch optimizers! (Source: Author)
Not just optimizers, because Torch also provides a host of different loss functions too! Here are some examples:
![](../images/body-35198fb19ef27157d293.png)
Some common PyTorch loss functions (Source: Author)
## 4. Layers and Modules
Just like we don't need to write our own optimizers, we don't need to declare raw tensors and matrix multiplication logic on our own (for the most part). Pytorch modules have us covered.
A PyTorch Module is the fundamental building block for all neural networks in PyTorch, acting as a container for layers, learnable parameters, and the logic for how data flows through them. For example, that linear layer we wrote earlier, where we manually declared the weights and biases, we can instead use these lines of code:
python

```
linear_model = nn.Linear(in_size, out_size) # Torch takes care of initializing weights
prediction = linear_model(input) # Forward pass
```

We learned how to make linear models (yay!), but what we really need to learn is how to train larger and deeper neural networks. The simplest type of neural network is the [**multi-layer perceptron**](https://en.wikipedia.org/wiki/Multilayer_perceptron) (MLP). An MLP is basically multiple linear layers with non-linear functions in between.
Creating MLPs is pretty straightforward in Torch. `nn.Sequential`is a common PyTorch module that is used to _sequentially_ pass the input through multiple layers. Here is the code:
python

```
# A 2 layer MLP
mlp_2_layers = nn.Sequential(
    nn.Linear(in_size, hidden_units),
    nn.ReLU(),
    nn.Linear(hidden_units, out_size)
)

# A 3 layer MLP
mlp_3_layers = nn.Sequential(
    nn.Linear(in_size, hidden_units),
    nn.ReLU(),
    nn.Linear(hidden_units, hidden_units),
    nn.ReLU(),
    nn.Linear(hidden_units, out_size)
)

```

Multi-layer perceptrons can learn compositional and non-linear functions! Here is an example of a zig-zag function and how a 2-layer MLP with RELU learns it.
![](../images/body-b83bf076e4eba4d03a62.gif)
A 2 layer MLP training on a piecewise linear function (Source: Author)
## 5. Writing custom networks
Torch has a vast array of awesome layers and modules that have inspired entire research papers. You can think about these as lego blocks that you can fit into and compose any neural network.
Want a convolutional network layer for images? Use `nn.Conv2d`.   
A GRU layer to process sequential tokens? Use `nn.GRU`
But most often in research, you would want to write a custom neural network architecture from scratch. The recipe for this process is as follows:
  1. Subclass from `nn.Module`
  2. In the `__init__` constructor function, initialize all your layers and weights
  3. Define a `forward()` where you write the logic of the forward pass


Here is an example where we implement the classic [ResNet](https://arxiv.org/abs/1512.03385) architecture:
python

```
class ResNetBlock(nn.Module):
    def __init__(self, in_channels, out_channels, stride=1, downsample=None):
        super(ResNetBlock, self).__init__()

        self.conv1 = nn.Conv2d(
            in_channels,
            out_channels,
            kernel_size=3,
            stride=stride,
            padding=1,
            bias=False,
        )
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.conv2 = nn.Conv2d(
            out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False
        )
        self.bn2 = nn.BatchNorm2d(out_channels)

        self.downsample = downsample

    def forward(self, x):
        residual = x

        out = F.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))

        if self.downsample:
            residual = self.downsample(x)

        out += residual
        out = F.relu(out)

        return out

```

That's it! You just initialize your layers and define the forward pass computation graph, and Torch will directly do the backward pass on its own. 
![](../images/body-624f57b4ef261645ec72.png)
A standard ResNet Block passes embeddings through a short stack of neural network layers (like convolution) and then adds the original embeddings back to the final output
Of course, you can use your custom layers and modules as parts of a much larger network! For example, here is an example of writing a single transformer block.
python

```
class AttentionLayer(nn.Module):
    def __init__(self, input_dim, attention_dim=64):
        super(SimpleAttention, self).__init__()

        # Linear layers for attention computation
        self.query = nn.Linear(input_dim, attention_dim)
        self.key = nn.Linear(input_dim, attention_dim)
        self.value = nn.Linear(input_dim, attention_dim)

        # Scaling factor
        self.scale = torch.sqrt(torch.FloatTensor([attention_dim]))

    def forward(self, x):
        # x shape: (batch_size, sequence_length, input_dim)
        batch_size, seq_len, input_dim = x.size()

        # Compute Q, K, V
        Q = self.query(x)  # (batch_size, seq_len, attention_dim)
        K = self.key(x)  # (batch_size, seq_len, attention_dim)
        V = self.value(x)  # (batch_size, seq_len, attention_dim)

        attention_scores = torch.matmul(Q, K.transpose(-2, -1)) / self.scale # Scaled dot-product attention
        attention_weights = F.softmax(attention_scores, dim=-1) # Convert attention weights to probabilities 
        attended_output = torch.matmul(attention_weights, V) # Apply attention to values

        return attended_output, attention_weights

class TransformerBlock(nn.Module):
    """
    A single transformer block composed of self-attention and a feed-forward network.
    """
    def __init__(self, embed_dim, ffn_hidden_dim):
        """
        Args:
            embed_dim (int): The dimensionality of the model's embeddings.
            ffn_hidden_dim (int): The dimensionality of the hidden layer in the FFN.
        """
        super(TransformerBlock, self).__init__()
        self.attention = SimpleAttention(embed_dim, embed_dim)
        self.norm1 = nn.LayerNorm(embed_dim)
        self.norm2 = nn.LayerNorm(embed_dim)
        
        self.ffn = nn.Sequential(
            nn.Linear(embed_dim, ffn_hidden_dim),
            nn.ReLU(),
            nn.Linear(ffn_hidden_dim, embed_dim)
        )

    def forward(self, x):
        """
        Forward pass for the transformer block.
        
        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, sequence_length, embed_dim).
            
        Returns:
            torch.Tensor: The output tensor of the transformer block.
        """
        # Self-attention part
        attended, _ = self.attention(x)
        # Add & Norm (residual connection)
        x = self.norm1(attended + x)
        
        # Feed-forward part
        ffn_out = self.ffn(x)
        # Add & Norm (residual connection)
        x = self.norm2(ffn_out + x)
        
        return x

class TransformerEncoder(nn.Module):
    """
    A transformer encoder that stacks multiple TransformerBlocks.
    """
    def __init__(self, num_layers, embed_dim, ffn_hidden_dim, seq_len, output_dim):
        """
        Args:
            num_layers (int): The number of transformer blocks to stack.
            embed_dim (int): The dimensionality of the model's embeddings.
            ffn_hidden_dim (int): The dimensionality of the hidden layer in the FFN.
            seq_len (int): The length of the input sequences.
            output_dim (int): The dimensionality of the final output (e.g., number of classes).
        """
        super(TransformerEncoder, self).__init__()
        
        # Create a list of transformer blocks
        self.layers = nn.ModuleList(
            [TransformerBlock(embed_dim, ffn_hidden_dim) for _ in range(num_layers)]
        )
        
        # Final classification head
        self.classifier = nn.Linear(embed_dim * seq_len, output_dim)

    def forward(self, x):
        """
        Forward pass for the full transformer encoder.
        
        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, sequence_length, embed_dim).
            
        Returns:
            torch.Tensor: The final output logits from the classifier.
        """
        # Pass input through all transformer blocks
        for layer in self.layers:
            x = layer(x)
        
        # Flatten the output for the classifier
        x = x.view(x.size(0), -1)
        
        # Final classification
        output = self.classifier(x)
        return output
```

Notice how the first module `AttentionLayer` computes [the scaled-dot-product attention](https://arxiv.org/abs/1706.03762). `TransformerBlock` applies layer norms and feedforward networks on top of it. And finally, the `TransformerEncoder` module applies multiple Transformer blocks in a sequence! And just like that, we have a [BERT model](https://arxiv.org/abs/1810.04805) that incorporates multiple stacks of bidirectional attention layers, along with various optimizations such as layer norms and residual connections.
> **If you are a beginner and this part overwhelms you, this is very much expected!** The cool thing with PyTorch is you get to choose the level of complexity you want to work with depending on your skill level.
> When you are beginning, you may want to stick to the hundreds of readymade modules Pytorch offers out of the box. You will slowly find the need to branch out and customizing them for your own use-case. And as you write a couple of custom ones on your own, you will grow more and more confident and proficient.
> The goal of this section was to show you the capabilities and infinite customization you can do by combining modules together. Remember: you write the forward pass, and as long as the full graph is differentiable, Torch will always be able to do the auto-differentiation for you!
## Next steps
The features and concepts covered in this article were handpicked to provide a whirlwind tour of some of Torch's most important capabilities. I have a YouTube video that explains all of these concepts, along with some additional ones like model deployment, dataloaders, distributions, and training methods.
That's it for this article! Here are some links where you can learn more about my work. Thanks for the read!
**Support me on Patreon:**<https://www.patreon.com/NeuralBreakdownwithAVB>
**My YouTube channel:**  
<https://www.youtube.com/@avb_fj>
**Follow me on Twitter:**  
<https://x.com/neural_avb>
**Read my articles:**   
<https://towardsdatascience.com/author/neural-avb/>
## Register Now to Continue Reading
### Unlock Towards Data Science with a Free Account
All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.
Register for freeSign in to your account
* * *
![](../images/body-849620ef9680d77fc51e.jpeg)
Written By
## [Avishek Biswas](https://towardsdatascience.com/author/neural.avb/)
[See all from Avishek Biswas](https://towardsdatascience.com/author/neural.avb/)
[Deep Dives](https://towardsdatascience.com/tag/deep-dives/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Neural Network](https://towardsdatascience.com/tag/neural-network/)[Pytorch](https://towardsdatascience.com/tag/pytorch/)[Tensor](https://towardsdatascience.com/tag/tensor/)
Share This Article
  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-deep-learning-with-pytorch-in-1-hour%2F&title=PyTorch%20Explained%3A%20From%20Automatic%20Differentiation%20to%20Training%20Custom%20Neural%20Networks)
  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-deep-learning-with-pytorch-in-1-hour%2F&title=PyTorch%20Explained%3A%20From%20Automatic%20Differentiation%20to%20Training%20Custom%20Neural%20Networks)
  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-deep-learning-with-pytorch-in-1-hour%2F&text=PyTorch%20Explained%3A%20From%20Automatic%20Differentiation%20to%20Training%20Custom%20Neural%20Networks)


Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.
[Write for TDS](https://towardsdatascience.com/submissions/)
## Related Articles
  * [![](../images/002.png)](https://towardsdatascience.com/a-comprehensive-guide-of-neural-networks-activation-functions-how-when-and-why-54d13506e4b8/)
## [A Comprehensive Guide of Neural Networks Activation Functions: How, When, and Why?](https://towardsdatascience.com/a-comprehensive-guide-of-neural-networks-activation-functions-how-when-and-why-54d13506e4b8/)
[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)
Is the quest of the perfect activation function accessible?
[Kevin Berlemont, PhD](https://towardsdatascience.com/author/kevin.berlemont/)
September 22, 20227 min read
  * [![](../images/003.png)](https://towardsdatascience.com/natural-language-processing-for-absolute-beginners-a195549a3164/)
## [Natural Language Processing For Absolute Beginners](https://towardsdatascience.com/natural-language-processing-for-absolute-beginners-a195549a3164/)
[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)
Solving complex NLP tasks in 10 lines of Python code
[Dmitrii Eliuseev](https://towardsdatascience.com/author/dmitryelj/)
September 2, 202310 min read
  * [![](../images/004.jpeg)](https://towardsdatascience.com/modelling-physiological-signal-estimation-as-a-deep-learning-problem-89dde307c3c5/)
## [Modelling Physiological Signal Estimation as a Deep Learning Problem](https://towardsdatascience.com/modelling-physiological-signal-estimation-as-a-deep-learning-problem-89dde307c3c5/)
[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)
Estimating vital signs like heart rate, breathing rate and SpO2 levels from facial videos using...
[Anwesh Marwade](https://towardsdatascience.com/author/anweshrm/)
May 3, 20219 min read
  * [![](../images/005.png)](https://towardsdatascience.com/tensorflow-2-0-here-is-what-ive-learned-from-a-i-day-at-google-64a31914610f/)
## [TensorFlow 2.0 - Here Is What I've Learned From A.I. Day At Google](https://towardsdatascience.com/tensorflow-2-0-here-is-what-ive-learned-from-a-i-day-at-google-64a31914610f/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
From Research, Prototype to Production
[Admond Lee](https://towardsdatascience.com/author/admond1994/)
July 6, 20197 min read
  * [![](../images/006.png)](https://towardsdatascience.com/linear-regression-from-scratch-e4db8c6d81db/)
## [Linear Regression & Gradient Descent](https://towardsdatascience.com/linear-regression-from-scratch-e4db8c6d81db/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
Learn about the most fundamental machine learning algorithm
[Slava Efimov](https://towardsdatascience.com/author/slavahead/)
November 12, 20226 min read
  * [![](../images/007.png)](https://towardsdatascience.com/shortening-model-deployment-with-tensorflow-d5a11044d0d/)
## [Shortening model deployment with TensorFlow](https://towardsdatascience.com/shortening-model-deployment-with-tensorflow-d5a11044d0d/)
[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)
How to make ML model deployment and serving easier with TensorFlow
[Dimitre Oliveira](https://towardsdatascience.com/author/dimitreoliveira/)
September 28, 202211 min read
  * [![](../images/008.png)](https://towardsdatascience.com/n-beats-the-first-interpretable-deep-learning-model-that-worked-for-time-series-forecasting-06920daadac2/)
## [N-BEATS - The First Interpretable Deep Learning Model That Worked for Time Series Forecasting](https://towardsdatascience.com/n-beats-the-first-interpretable-deep-learning-model-that-worked-for-time-series-forecasting-06920daadac2/)
[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)
An easy-to-understand deep dive into how N-BEATS works and how you can use it.
[Jonte Dancker](https://towardsdatascience.com/author/jodancker/)
May 11, 202411 min read
  * [![](../images/009.jpg)](https://towardsdatascience.com/what-is-amazon-ec2-and-how-to-use-it-2f621210cf4a/)
## [What is Amazon EC2 and how to use it?](https://towardsdatascience.com/what-is-amazon-ec2-and-how-to-use-it-2f621210cf4a/)
[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)
Train your models with GPU instances on the AWS cloud.
[NVS Yashwanth](https://towardsdatascience.com/author/nvsyashwanth/)
October 1, 202010 min read
  * [![](../images/010.jpg)](https://towardsdatascience.com/principal-component-analysis-from-scratch-in-numpy-61843da1f967/)
## [Principal Component Analysis From Scratch in Numpy](https://towardsdatascience.com/principal-component-analysis-from-scratch-in-numpy-61843da1f967/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
It started like a times series project. It ended up being a PCA project.
[Guillermina Sutter Schneider](https://towardsdatascience.com/author/gsutter/)
December 10, 20205 min read


  * [YouTube](https://www.youtube.com/c/TowardsDataScience)
  * [X](https://x.com/TDataScience)
  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)
  * [Threads](https://www.threads.net/@towardsdatascience)
  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)


[](https://towardsdatascience.com/)
Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.
Subscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)
© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)
####  Recommended Articles 
Close
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ "Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ "The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ "Does Your Company Have a Data Strategy?")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ "Productivity Tips, Data Career Insights, and Other Recent Must-Reads")


