
Hugging Face Blog
· 2 min read
Profiling in PyTorch (Part 2): From nn.Linear to a Fused MLP
In the first part of this series "Profiling in PyTorch", we used torch.add(torch.matmul(x, w), b) to learn how to read PyTorch profiler traces. We also discussed several other topics that came our way - the CPU dispatch chain, launch overhead, the difference between an overhead-bound and a compute-bound regime, and some internals of torch.compile.
In the second iteration (this blog post), we climb one rung up the ladder. We replace the hand-written matmul-add pair with an nn.Linear (with bias=True). This is the building block every deep learning model uses. We then stack three of them (specific to our example), with an activation in between, to form a Multilayer Perceptron (MLP) block.
The scripts for this blog post live here: 02_linear.py, 03_simple_mlp.py, and 03_kernels_mlp.py. Like before, it helps to open them in a separate tab and walk through the code as you read. We use an
NVIDIA A100-SXM4-80GBGPU to run the scripts. It is really easy to set up a GPU on the Hugging Face infrastructure and experiment with the scripts using Dev Mode with Spaces. One could also run the scripts with the Hugging Face Jobs pipeline.
Before we begin, a quick recap of two ideas we will lean on repeatedly:
- A GPU kernel is a program that runs in parallel on many threads of the GPU.
- The CPU schedules and launches these kernels. Most of the PyTorch overhead you see in a profiler trace is this scheduling work.
From matmul-add to Linear
nn.Linear is a module wrapper around the same matrix multiplication and addition we already profiled in Part 1. The only difference is that it owns its weight and bias as parameters and exposes a forward method that PyTorch users have grown familiar with.
# bias=True would truly emulate the multiplication and addition
# operations we have seen in part 1 of the series
linear_layer = nn.Linear(in_dim, out_dim, bias=True)
y = linear_layer(x)
The operation at hand can be written as:
y = x @ w.T + b
Figure 1: Profiler trace of nn.Linear |
Original source
This story was published by Hugging Face Blog. SyncAI.news shows a preview; the complete article is on the publisher's site.
Read the full story on huggingface.co


