> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Multilayer Perceptron (MLP)

> The feed-forward block of a transformer.

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/nlp/transformers/mlp/index.ipynb)

Multi-head self-attention mixes information across tokens: each output is a weighted average of value vectors. The weights depend non-linearly on the input, through the softmax, but each output is still a weighted average of linear projections of the tokens. The MLP adds a separate, feature-wise non-linear transformation that is applied to each token on its own, after the tokens have exchanged information. In a conventional dense transformer with hidden width $4d$, the MLP has $8d^2$ weights against $4d^2$ for the attention projections, about two thirds of the matrix weights of the block, not counting biases and normalization parameters.

Continuing the notation of the [multi-head attention](https://aegean.ai/aiml-common/lectures/nlp/transformers/multihead-self-attention/index.md) section, where $\hat Z$ is the output of the attention block, the MLP sub-block is

$$
\begin{aligned}
Y &= \mathtt{LayerNorm}(\hat Z) \\
\tilde X &= \mathtt{MLP}(Y) + \hat Z
\end{aligned}
$$

As in the attention block, a skip connection adds the input to the MLP output. The MLP itself is two linear layers with an activation in between, usually a ReLU or a GELU. The GELU weighs its input by the probability that a standard Gaussian variable is smaller, $\mathrm{GELU}(x) = x\,\Phi(x)$, so it is a smooth gating function resembling ReLU but not monotone everywhere.

![Output from cell 1](https://mintcdn.com/aegeanaiinc/0ApiccrGMnyvyrYq/aiml-common/lectures/nlp/transformers/mlp/images/cell_1_output_1.svg?fit=max\&auto=format\&n=0ApiccrGMnyvyrYq\&q=85\&s=a23c57d36ee6f4b743128c008e28e531)

Unlike the ReLU, the GELU is smooth at 0 and slightly negative for small negative inputs.

The code below implements the MLP, also called the feed-forward layer, with the feed-forward sizes of BERT-base (which uses post-LN, unlike the pre-LN equations above): $d = 768$ and a hidden width of $4d = 3072$.

> [accordion] Code
>
> ```python theme={null}
> from types import SimpleNamespace
>
> import torch.nn as nn
>
> torch.manual_seed(0)
>
>
> class FeedForward(nn.Module):
>     def __init__(self, config):
>         super().__init__()
>         self.linear_1 = nn.Linear(config.hidden_size, config.intermediate_size)
>         self.linear_2 = nn.Linear(config.intermediate_size, config.hidden_size)
>         self.gelu = nn.GELU()
>         self.dropout = nn.Dropout(config.hidden_dropout_prob)
>
>     def forward(self, x):
>         x = self.linear_1(x)
>         x = self.gelu(x)
>         x = self.linear_2(x)
>         x = self.dropout(x)
>         return x
>
>
> config = SimpleNamespace(hidden_size=768, intermediate_size=3072, hidden_dropout_prob=0.1)
> ff = FeedForward(config).eval()  # eval mode turns dropout off
>
> d = config.hidden_size
> mlp_weights = ff.linear_1.weight.numel() + ff.linear_2.weight.numel()
> attention_weights = 4 * d * d  # W^q, W^k, W^v and W^o
> print(f"MLP weights:       {mlp_weights:,} = {mlp_weights / d**2:.0f} d^2")
> print(f"attention weights: {attention_weights:,} = 4 d^2")
> print(f"MLP share of the block: {mlp_weights / (mlp_weights + attention_weights):.2f}")
> ```

```output theme={null}
MLP weights:       4,718,592 = 8 d^2
attention weights: 2,359,296 = 4 d^2
MLP share of the block: 0.67
```

In evaluation mode (dropout disabled), the MLP processes each token independently of the other tokens. If the tokens of the input are shuffled, its outputs are shuffled in the same way and are otherwise unchanged. The next cell checks this.

> [accordion] Code
>
> ```python theme={null}
> x = torch.randn(10, d)  # 10 tokens
> perm = torch.randperm(10)
> with torch.no_grad():
>     same = torch.allclose(ff(x)[perm], ff(x[perm]), atol=1e-6)
> print("shuffling the tokens only shuffles the outputs:", same)
> ```

```output theme={null}
shuffling the tokens only shuffles the outputs: True
```

In this standard block, attention is the only operation that directly exchanges information across token positions. The MLP then transforms each token's embedding with the same weights.

## PyTorch reference

| PyTorch class | Description |
| - | - |
| [`nn.Linear`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.Linear.html) | Affine map of the input: $y = xA^T + b$. |
| [`nn.GELU`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.GELU.html) | Gaussian Error Linear Unit activation. |
| [`nn.ReLU`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.ReLU.html) | Rectified linear unit, applied element-wise. |
| [`nn.Dropout`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.Dropout.html) | During training, zeroes random elements of the input with probability $p$. |
| [`nn.LayerNorm`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.LayerNorm.html) | Layer normalization over the last dimensions of the input. |

Key references: (Vaswani et al., 2017; Ramachandran et al., 2017); Hendrycks and Gimpel, Gaussian Error Linear Units (GELUs), 2016, [arXiv:1606.08415](https://arxiv.org/abs/1606.08415).

## References

* Ramachandran, P., Zoph, B., Le, Q. (2017). *Searching for Activation Functions*. arXiv \[cs.NE]. [Link](http://arxiv.org/abs/1710.05941)
* Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., et al. (2017). *Attention Is All You Need*. arXiv \[cs.CL]. [Link](http://arxiv.org/abs/1706.03762)

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/nlp/transformers/mlp).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.