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

# Transformers and Self-Attention

> Transformers and self-attention.

[![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/transformers-intro/index.ipynb)

The [GPT from scratch](https://aegean.ai/aiml-common/lectures/nlp/transformers/gpt-from-scratch/gpt-from-scratch.md) section builds a decoder-only transformer, the architecture GPT uses, in code.

Compared to the RNNs of the earlier chapters, the transformer architecture makes two changes.

1. It removes all recurrent connections. During training, all positions of a sequence are then processed in parallel, and at inference the model reads the whole prompt in one parallel pass. Generating text is still sequential, because each new token depends on the tokens before it. Since the processing no longer follows the order of the tokens, the order has to be encoded explicitly, through positional information, either in the input embeddings or inside attention. The [cross-attention and position encoding](https://aegean.ai/aiml-common/lectures/nlp/transformers/cross-attention-position-encoding/index.md) section covers the methods.

2. It uses attention to *adjust* context-free embeddings, such as the word2vec embeddings, based on the context of the input sequence. Attention can sit in the encoder, in the decoder, or in both. The name comes from what the mechanism does: each token attends to the other tokens of the input sequence, and the attention weights decide how much each token contributes to the update.

The figure below shows the two transformer architectures you meet in this chapter. The original transformer has an encoder and a decoder (Vaswani et al., 2017). The encoder reads the whole source sentence. The decoder generates the output one token at a time and reads the encoder output through cross-attention. GPT and most current language models keep only the decoder.

Both architectures stack $N$ identical layers, and each layer alternates two kinds of computation. In the attention sublayers, shown in orange, tokens exchange information, and these are the only places where they do. In the MLP sublayers, shown in blue, each token is transformed on its own, with the same weights for every token. A residual connection adds the input of each sublayer to its output.

![Encoder-decoder and decoder-only transformer architectures. Each layer contains attention sublayers, where tokens exchange information, and an MLP sublayer that transforms each token on its own; residual connections add each sublayer's input to its output](https://mintcdn.com/aegeanaiinc/Yrt_S4TWwKs8h38s/aiml-common/lectures/nlp/transformers/transformers-intro/images/transformer-architectures.svg?fit=max\&auto=format\&n=Yrt_S4TWwKs8h38s\&q=85\&s=12651fb06a9e20e5e8935aab1f41f814)

*Encoder-decoder and decoder-only transformers. Layer normalization is not drawn.*

Most language models released since 2020 are decoder-only transformers that refine the right half of this figure. The [model releases](https://aegean.ai/research/models/index.md) page lists the major models with their technical reports. The reports below draw the architecture of their model, and you can compare each drawing with the figure above.

* GPT-1, Figure 1 (left): a 12-layer decoder-only transformer with masked self-attention, trained to predict the next token (Radford et al., n.d.).
* Llama 3, Figure 1: a dense decoder-only transformer, close to the original design. Its attention uses grouped-query attention, where several query heads share one key-value head (Grattafiori et al., 2024).
* Mixtral, Figure 1: the MLP of each layer becomes a mixture of experts. A router sends each token to 2 of 8 MLPs and adds their weighted outputs (Jiang et al., 2024).
* DeepSeek-V3, Figure 2: a mixture of experts in place of the MLP, and multi-head latent attention, which compresses the keys and values so that less memory is needed during generation (DeepSeek-AI et al., 2024).

In all four, the split of the figure above still holds: attention is where tokens exchange information, and the MLP or its mixture of experts acts on each token on its own.

To see what self-attention changes, consider the token *bears* in three sentences:

* I love *bears*
* She *bears* the pain
* *Bears* won the game

The token has a different meaning in each sentence: an animal, tolerating something, and a sports team. Assume a tokenizer that maps all three occurrences to the same token ID (for example, an uncased tokenizer). Their lookup embeddings are then identical, although position embeddings may differ. A bidirectional encoder can produce different contextual representations by combining information from the surrounding tokens. A causal decoder can use only the prefix through the current token; in particular, the first token of the third sentence cannot yet use "won the game".

## Simple self-attention mechanism

The simplest way to let the other tokens affect a context-free representation is a dot product between the input token $x_i$ and every token of the context. This is called simple *self-attention*. The word "self" means that each token attends to the tokens of its own sequence. The simple version uses the input vectors directly, with no learned transformation.

The next figure shows the input context matrix $X$ with dimensions $T \times d$, where $T$ is the length of the input context and $d$ is the embedding dimension. In this example each token occupies a row with $d$ features with $d=4$, and there are $T=3$ tokens. Real models are much larger: [Qwen3.8-27B](https://huggingface.co/Qwen/Qwen3.8-27B) uses $d=5120$ and a context of up to $T=262{,}144$ tokens.

![Simple self-attention: X times X transpose gives the T by T scores S, a softmax over each row gives the weights A, and A times X gives the output, one updated row per token](https://mintcdn.com/aegeanaiinc/Yrt_S4TWwKs8h38s/aiml-common/lectures/nlp/transformers/transformers-intro/images/simple-self-attention.svg?fit=max\&auto=format\&n=Yrt_S4TWwKs8h38s\&q=85\&s=1559d2be4db28c658ec7fb5e2a66c76a)

*Simple self-attention on a context of three tokens. The input $X$ plays all three roles: it is compared with itself to give the scores, and it is also what the weights average.*

Inputs usually also carry a batch dimension $B$, so $X$ is a tensor of shape $B \times T \times d$. This section ignores batching.

Self-attention updates the embedding $x_i$ of the $i$-th token in three steps.

The first step computes the attention scores $s_{ij} = x_i^T x_j$. Each score is the dot product of the input token with one token $j$ of the context, including the input token itself. With 3 tokens there are 3 scores per token, so the scores form a $3 \times 3$ matrix.

The second step passes each row of scores through a softmax to obtain the *attention weights* $\alpha_{ij}$. The softmax maps a vector to a vector of values between 0 and 1 that sum to 1. It is applied across the tokens of the context, so each input token gets $T=3$ attention weights. Each row is a categorical distribution over the available positions, but it is not a prediction of a class label or a calibrated explanation. For finite, unmasked scores it makes all attention weights positive and makes the tokens of the context compete for weight:

$$
\alpha_{ij} \ge 0, \qquad \sum_{j=1}^T \alpha_{ij} = 1.
$$

A large attention weight on one token comes at the expense of the weights on the other tokens. In the limiting case, when token $i$ puts all of its weight on itself ($\alpha_{ii} = 1$ and $\alpha_{ij} = 0$ for $j \ne i$), its embedding stays unchanged.

The third step uses the attention weights to form a weighted sum of the token embeddings. The result is the new embedding of the input token, which now includes information from the other embeddings of the input sequence:

$$
\hat x_i = \sum_{j=1}^T \alpha_{ij} x_j.
$$

All three steps fit into one equation, with the softmax applied to each row:

$$
\hat X = \mathtt{softmax}(XX^T)X.
$$

The code below runs the three steps on a random context with $T=3$ and $d=4$.

> [accordion] Code
>
> ```python theme={null}
> import torch
>
> torch.manual_seed(0)
> torch.set_printoptions(precision=2, sci_mode=False)
>
> T, d = 3, 4
> X = torch.randn(T, d)  # input context, one token per row
>
> S = X @ X.T  # attention scores s_ij
> A = torch.softmax(S, dim=-1)  # attention weights, softmax over each row
> X_hat = A @ X  # output embeddings
>
> print("scores S:\n", S)
> print("weights A:\n", A)
> print("row sums:", A.sum(dim=-1))
> print("output shape:", tuple(X_hat.shape))
> ```

```output theme={null}
scores S:
 tensor([[ 7.53, -1.66,  0.41],
        [-1.66,  4.00,  1.26],
        [ 0.41,  1.26,  1.07]])
weights A:
 tensor([[1.00, 0.00, 0.00],
        [0.00, 0.94, 0.06],
        [0.19, 0.44, 0.37]])
row sums: tensor([1., 1., 1.])
output shape: (3, 4)
```

This version has no trainable parameters, and it has a weakness. The score of a token with itself, $x_i^T x_i = \lVert x_i \rVert^2$, is usually the largest in its row for the independent random embeddings used here, so each token attends mostly to itself. In the output above, the first token puts almost all of its weight on itself. The third token is the exception: its own score (1.07) is smaller than its score with the second token (1.26), because its embedding is short.

The exception becomes rare as the embedding dimension grows. For random embeddings with unit-variance entries, $\lVert x_i \rVert^2$ is about $d$, while the dot product of two different tokens has a typical size of only $\sqrt d$. The next cell counts, over 1000 random contexts of $T=8$ tokens, how often a token's largest weight is on itself.

> [accordion] Code
>
> ```python theme={null}
> for d in (4, 16, 64):
>     X = torch.randn(1000, 8, d)  # 1000 random contexts of 8 tokens
>     A = torch.softmax(X @ X.transpose(1, 2), dim=-1)
>     self_is_max = (A.argmax(dim=-1) == torch.arange(8)).float().mean()
>     self_weight = A.diagonal(dim1=1, dim2=2).mean()
>     print(f"d={d:3d}: largest weight on itself {self_is_max:.0%}, mean self weight {self_weight:.2f}")
> ```

```output theme={null}
d=  4: largest weight on itself 72%, mean self weight 0.57
d= 16: largest weight on itself 100%, mean self weight 0.99
d= 64: largest weight on itself 100%, mean self weight 1.00
```

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

For these random embeddings, the weight matrix at $d=64$ is close to the identity, so $\hat X \approx X$. This is not a universal property of real embeddings. Learned projections allow the model to replace the fixed similarity function with a trainable compatibility function.

## The output as a move inside the convex hull

The weights of each row are non-negative and sum to one, so $x_i = \sum_j \alpha_{ij} x_i$. Subtracting this from the output gives

$$
\hat x_i = x_i + \Delta_i, \qquad \Delta_i = \sum_{j=1}^T \alpha_{ij}\,(x_j - x_i).
$$

You can read the update as a move. The token starts at $x_i$ and is displaced by $\Delta_i$, the weighted average of the vectors that point from $x_i$ to each token of the context. The move is bounded. A weighted average with non-negative weights that sum to one always lies in the *convex hull* of the tokens, the smallest convex region that contains all of them. The move can bring the token closer to some tokens and farther from others, but it cannot carry the token outside that region.

The next figure shows the move of $x_1$ in a context of four tokens with $d=2$.

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

*The weights are the softmax of the scores $x_1^T x_j$. Token $x_1$ keeps 0.44 of its weight on itself and gives 0.39 to $x_2$, so $\hat x_1$ moves only part of the way toward $x_2$ and stays inside the hull.*

A full transformer layer adds the attention output to $x_i$ through a residual connection, so there the update is a literal addition. In that layer the tokens pass through learned linear maps before they are averaged, so the update is no longer confined to the convex hull of the input tokens.

Think of attention as a soft lookup in a collection of records. Each record has a key used for matching and a value used for retrieval. A query is compared with every available key, and the retrieved values are combined using the resulting weights. In self-attention each token supplies all three: a query, a key and a value. The [next section](https://aegean.ai/aiml-common/lectures/nlp/transformers/singlehead-self-attention/index.md) develops this idea.

## PyTorch reference

| PyTorch class | Description |
| - | - |
| [`nn.Embedding`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.Embedding.html) | A lookup table of embeddings for a fixed vocabulary. |
| [`nn.Linear`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.Linear.html) | Affine map of the input: $y = xA^T + b$. |
| [`nn.Softmax`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.Softmax.html) | Softmax over one dimension of a tensor. |
| [`nn.MultiheadAttention`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.MultiheadAttention.html) | Attention with several heads in parallel. |
| [`nn.TransformerEncoderLayer`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.TransformerEncoderLayer.html) | Self-attention followed by a feed-forward network. |
| [`nn.TransformerDecoderLayer`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.TransformerDecoderLayer.html) | Self-attention, cross-attention and a feed-forward network. |

Key references: (Bahdanau et al., 2014; Luong et al., 2015; Vaswani et al., 2017)

## References

* Bahdanau, D., Cho, K., Bengio, Y. (2014). *Neural Machine Translation by Jointly Learning to Align and Translate*. arXiv \[cs.CL]. [Link](http://arxiv.org/abs/1409.0473)
* Grattafiori, A., Dubey, A., Jauhri, A., Pandey, A., Kadian, A., et al. (2024). *The Llama 3 herd of models*. arXiv \[cs.AI]. [Link](http://arxiv.org/abs/2407.21783)
* Jiang, A., Sablayrolles, A., Roux, A., Mensch, A., Savary, B., et al. (2024). *Mixtral of Experts*. arXiv \[cs.LG]. [Link](http://arxiv.org/abs/2401.04088)
* Luong, M., Pham, H., Manning, C. (2015). *Effective Approaches to Attention-based Neural Machine Translation*. arXiv \[cs.CL]. [Link](http://arxiv.org/abs/1508.04025)
* Radford, A., Narasimhan, K., Salimans, T., Sutskever, I. (n.d.). *Improving Language Understanding by Generative Pre-Training*. [Link](https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf)
* 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)
* DeepSeek-AI, Liu, A., Feng, B., Xue, B., Wang, B., et al. (2024). *DeepSeek-V3 Technical Report*. arXiv \[cs.CL]. [DOI](https://doi.org/10.48550/arXiv.2412.19437)

***

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/transformers-intro).


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