Skip to main content
Open In Colab 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 4d4d, the MLP has 8d28d^2 weights against 4d24d^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 section, where Z^\hat Z is the output of the attention block, the MLP sub-block is Y=LayerNorm(Z^)X~=MLP(Y)+Z^\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, GELU(x)=x Φ(x)\mathrm{GELU}(x) = x\,\Phi(x), so it is a smooth gating function resembling ReLU but not monotone everywhere. Output from cell 1 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=768d = 768 and a hidden width of 4d=30724d = 3072.
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.
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

Key references: (Vaswani et al., 2017; Ramachandran et al., 2017); Hendrycks and Gimpel, Gaussian Error Linear Units (GELUs), 2016, arXiv:1606.08415.

References

  • Ramachandran, P., Zoph, B., Le, Q. (2017). Searching for Activation Functions. arXiv [cs.NE]. Link
  • Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., et al. (2017). Attention Is All You Need. arXiv [cs.CL]. Link

Found an error on this page? Report an issue.