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

# Single-Head Self-Attention

> Scaled dot-product self-attention with queries, keys and values.

[![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/singlehead-self-attention/index.ipynb)

## Scaled dot-product self-attention

The [simple attention mechanism](https://aegean.ai/aiml-common/lectures/nlp/transformers/transformers-intro/index.md) compares input vectors directly. Its compatibility function has no trainable parameters, although its input embeddings may already have been learned.

Consider "I love bears", "She bears the pain" and "Bears won the game". The word plays different grammatical and semantic roles.

How can the model learn which information to exchange between tokens? We separate the problem into deciding which tokens to read from and deciding what information to retrieve from them.

### Linear transformation of the input embeddings

Instead of comparing the input vectors directly, we learn three feature maps. These are not necessarily invertible changes of coordinates; they can reduce dimension and discard information. The purpose of these maps is to learn features that make contextually relevant tokens compatible, even when their original embeddings are dissimilar.

We define three trainable matrices $W^q, W^k, W^v$ and project each token, or equivalently the matrix $X$, into three different spaces:

$$
\begin{aligned}
Q &= XW^q \\
K &= XW^k \\
V &= XW^v
\end{aligned}
$$

Here $X$ is the $T \times d$ input embedding matrix, where $T$ is the input sequence length and $d$ is the embedding dimension. $Q$, $K$ and $V$ hold the queries, keys and values. The matrices $W^q, W^k, W^v$ have dimensions $d \times d_q$, $d \times d_k$ and $d \times d_v$. Queries and keys live in a space of the same dimension, so $d_q = d_k$.

For token $i$, the query $q_i$ is used to compare against keys $k_j$ from all allowed positions. The value $v_j$ is the information contributed by position $j$. A large query-key dot product gives a larger relative weight, all else equal. It is not necessarily a small Euclidean distance.

Consider "I love bears". The words `love` and `bears` are not semantically similar, but they participate in a verb-object relationship. Imagine a head whose query features express a request for a governing verb and whose key features indicate the ability to supply that information. The query of `bears` and the key of `love` could then align in the query-key space, even if their original embeddings were nearly orthogonal. In "She bears the pain", a different pattern could be useful: the verb `bears` can receive information from its subject `She` or, in bidirectional attention, its object `pain`.

These are linguistic analogies for learned features, not a claim that individual coordinates are labeled with grammatical roles. A head may learn such relationships through training, without explicit grammatical supervision. The value projection determines which features of the matched token are actually passed on.

### Moving the weight off the token itself

In the [simple mechanism](https://aegean.ai/aiml-common/lectures/nlp/transformers/transformers-intro/index.md) a token usually puts most of its weight on itself, because its score with itself is its squared norm. The query and key maps can change that.

Take three orthogonal unit embeddings for `I`, `love` and `bears`. Under simple attention, `bears` has a score of 0 with `love` and a score of 1 with itself. The two maps below send the query of `bears` and the key of `love` along the same direction of a two-dimensional query-key space. They send the keys of `I` and `bears` along the orthogonal direction. The matrices are written by hand to show what the maps can do. Training finds such matrices from data.

> [accordion] Code
>
> ```python theme={null}
> import torch
>
> torch.set_printoptions(precision=2, sci_mode=False)
>
> words = ["I", "love", "bears"]
> X_demo = torch.eye(3)  # orthogonal unit embeddings, one token per row
> Wq_demo = torch.tensor([[0.0, 1.0], [0.0, 1.0], [1.5, 0.0]])
> Wk_demo = torch.tensor([[0.0, 1.0], [1.5, 0.0], [0.0, 1.0]])
>
> simple = torch.softmax(X_demo[2] @ X_demo.T, dim=0)  # weights of bears, simple attention
>
> q_bears = X_demo[2] @ Wq_demo
> K_demo = X_demo @ Wk_demo
> learned = torch.softmax(q_bears @ K_demo.T, dim=0)  # weights of bears with the maps
>
> print("weights of bears, simple attention:", simple)
> print("weights of bears, query and key maps:", learned)
> ```

```output theme={null}
weights of bears, simple attention: tensor([0.21, 0.21, 0.58])
weights of bears, query and key maps: tensor([0.09, 0.83, 0.09])
```

![Output from cell 2](https://mintcdn.com/aegeanaiinc/0ApiccrGMnyvyrYq/aiml-common/lectures/nlp/transformers/singlehead-self-attention/images/cell_2_output_1.svg?fit=max\&auto=format\&n=0ApiccrGMnyvyrYq\&q=85\&s=2269ec547722c1ffdc0745c416d6fda8)

With simple attention, `bears` keeps 0.58 of its weight on itself. With the two maps it puts 0.83 of its weight on `love`. A trained head learns many such directions at once, and one relationship can spread over many coordinates of the query-key space.

The query and key maps decide the weights. The value map $W^v$ decides what is averaged. In the simple mechanism the output $\hat x_i$ is a weighted average of the input tokens, so it stays in their [convex hull](https://aegean.ai/aiml-common/lectures/nlp/transformers/transformers-intro/index.md). With the value map, the output is a weighted average of the values $v_j = x_j W^v$. It stays in the convex hull of the values, which need not lie inside the hull of the inputs.

The embeddings here are the three unit vectors, so the coordinates of a point are its weights on `I`, `love` and `bears`. A point lies in the convex hull of the three tokens when its coordinates are non-negative and sum to one. The value map below moves all three values. Each row of $W^v$ sums to one, so the values stay in the plane of the tokens and the figure can draw them there. The value of `love` lands past `love`, on the side away from `I`. The values of `I` and `bears` move outward too.

> [accordion] Code
>
> ```python theme={null}
> Wv_demo = torch.tensor([[1.2, -0.4, 0.2], [-0.6, 1.4, 0.2], [0.1, -0.25, 1.15]])
> V_demo = X_demo @ Wv_demo
>
>
> def in_hull(c):
>     """True if the point with token coordinates c lies in the hull of the three tokens."""
>     return bool((c >= 0).all() and torch.isclose(c.sum(), torch.tensor(1.0)))
>
>
> x_hat_simple = simple @ X_demo  # average of the input tokens
> x_hat_learned = learned @ V_demo  # average of the values
>
> print("x_hat of bears, simple attention:", x_hat_simple, " in hull:", in_hull(x_hat_simple))
> print("x_hat of bears, learned maps:    ", x_hat_learned, " in hull:", in_hull(x_hat_learned))
> ```

```output theme={null}
x_hat of bears, simple attention: tensor([0.21, 0.21, 0.58])  in hull: True
x_hat of bears, learned maps:     tensor([-0.38,  1.10,  0.28])  in hull: False
```

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

*The plane of the three tokens. Each thin orange arrow takes a token to its value. Both thick arrows start at `bears`. Under simple attention the output stays in the blue triangle. With the learned maps the output is an average of the values, and it leaves the blue triangle.*

The output with the learned maps has a negative weight on `I`, so it lies outside the hull of the input tokens. It is still inside the hull of the values, shown dashed.

For a single head, the output always lies in the convex hull of the values. Whatever the query and key maps compute, the weights of each row are non-negative and sum to one. So $\hat x_i = \sum_j \alpha_{ij} v_j$ is a convex combination of the values that token $i$ may attend to. With a causal mask, these are the values at positions up to $i$.

This hull is small. With two tokens it is a line segment, and attention only decides how far $x_i$ moves along the segment toward the other token. Three tokens give at most a triangle, and four tokens give at most a tetrahedron. In general, $T$ values of dimension $d_v$ span a region of dimension

$$
\dim \operatorname{conv}\{v_1, \ldots, v_T\} \le \min(T-1,\, d_v).
$$

A ten-token sentence in Qwen3.8-27B, with $d=5120$, has a hull of at most nine dimensions. The value map does not enlarge it. A linear map sends the hull of the inputs onto the hull of the values, so it can move, rotate, scale or flatten the region, but it cannot raise its dimension.

The other parts of the layer lift these limits. Each head of multi-head attention computes its own weights and its own values, and the layer combines the head outputs, so the result is no longer confined to the hull of one set of values. The residual connection adds the attention output to $x_i$ as an update. The MLP then applies a nonlinear map to each token on its own.

The rest of this section works with a random context of $T=8$ tokens, embedding dimension $d=16$ and query-key dimension $d_k=4$. The next cell draws the embeddings and the three projection matrices.

> [accordion] Code
>
> ```python theme={null}
> import math
>
> import torch
> import torch.nn.functional as F
>
> torch.manual_seed(0)
> torch.set_printoptions(precision=2, sci_mode=False)
>
> T, d, d_k = 8, 16, 4
> X = torch.randn(T, d)  # input embeddings, one token per row
>
> W_q = torch.randn(d, d_k) / math.sqrt(d)
> W_k = torch.randn(d, d_k) / math.sqrt(d)
> W_v = torch.randn(d, d_k) / math.sqrt(d)
>
> Q, K, V = X @ W_q, X @ W_k, X @ W_v
> print("Q:", tuple(Q.shape), " K:", tuple(K.shape), " V:", tuple(V.shape))
> ```

```output theme={null}
Q: (8, 4)  K: (8, 4)  V: (8, 4)
```

### Computation of the attention scores

Write the input matrix $X$ and the query weight matrix $W^q$ element by element (the key weight matrix is analogous):

$$
X = \begin{bmatrix}
x_{1,1} & x_{1,2} & \cdots & x_{1,d} \\
x_{2,1} & x_{2,2} & \cdots & x_{2,d} \\
\vdots & \vdots & \ddots & \vdots \\
x_{T,1} & x_{T,2} & \cdots & x_{T,d}
\end{bmatrix},
\qquad
W^q = \begin{bmatrix}
w_{1,1} & \cdots & w_{1,d_k} \\
\vdots & \ddots & \vdots \\
w_{d,1} & \cdots & w_{d,d_k}
\end{bmatrix}
$$

The product $Q = XW^q$ has dimensions $T \times d_k$. Each element $q_{i,j}$ of $Q$ is

$$
q_{i,j} = \sum_{l=1}^{d} x_{i,l} \, w_{l,j}.
$$

Each column $j$ of $W^q$ is a set of weights over the $d$ features of the input embedding. So the projection can weigh some features of a token more than others when it computes the token's query, and the same holds for the key.

The dot product now happens in the query-key space of dimension $d_k$. Treat $x_i$ as a row of $X$, a $1 \times d$ row vector. The query of token $i$ is $q_i = x_i W^q$ and the key of token $j$ is $k_j = x_j W^k$, so

$$
\begin{aligned}
q_i k_j^T &= x_i W^q (W^k)^T x_j^T = x_i W x_j^T, \\
W &= W^q (W^k)^T,
\end{aligned}
$$

where $W$ is a $d \times d$ matrix of rank at most $d_k$. Compared to the simple mechanism, the plain dot product $x_i x_j^T$ becomes a learned bilinear form. The next cell checks both statements numerically.

> [accordion] Code
>
> ```python theme={null}
> W = W_q @ W_k.T  # d x d matrix of the bilinear form
> print("Q K^T equals X W X^T:", torch.allclose(Q @ K.T, X @ W @ X.T, atol=1e-5))
> print("W is", tuple(W.shape), "with rank", torch.linalg.matrix_rank(W).item())
> ```

```output theme={null}
Q K^T equals X W X^T: True
W is (16, 16) with rank 4
```

Geometrically you can picture it as shown below.

![Queries and keys in the query-key space](https://mintcdn.com/aegeanaiinc/Yrt_S4TWwKs8h38s/aiml-common/lectures/nlp/transformers/singlehead-self-attention/images/self-attention-vectors.png?fit=max\&auto=format\&n=Yrt_S4TWwKs8h38s\&q=85\&s=da058a2ab2facadd12dd9be999364f92)

*The diagram illustrates a possible alignment. The dot product depends on both vector norms and the angle between them. The query and keys only decide the attention weights. What is added to the token's output comes from the value vectors of the tokens it attends to.*

In matrix form, the scores are

$$
S = QK^T.
$$

### Scaling

The scores are divided by the square root of the key dimension, $\sqrt{d_k}$. Without this division, large score differences can cause the softmax to saturate: the largest score takes almost all of the weight and the weights of the other tokens shrink toward zero.

The experiment below shows this behavior. It applies the softmax to a vector of 8 scores, and then to the same vector multiplied by 100.

> [accordion] Code
>
> ```python theme={null}
> def softmax(x):
>     e_x = torch.exp(x - x.max())  # subtracting the max avoids overflow
>     return e_x / e_x.sum()
>
>
> scores = torch.tensor([0.171, 0.041, 0.079, 0.062, 0.192, 0.222, 0.115, 0.117])
> print("softmax(scores):      ", softmax(scores))
> print("softmax(100 * scores):", softmax(100 * scores))
> ```

```output theme={null}
softmax(scores):       tensor([0.13, 0.11, 0.12, 0.12, 0.13, 0.14, 0.12, 0.12])
softmax(100 * scores): tensor([0.01, 0.00, 0.00, 0.00, 0.05, 0.95, 0.00, 0.00])
```

![Output from cell 8](https://mintcdn.com/aegeanaiinc/0ApiccrGMnyvyrYq/aiml-common/lectures/nlp/transformers/singlehead-self-attention/images/cell_8_output_1.svg?fit=max\&auto=format\&n=0ApiccrGMnyvyrYq\&q=85\&s=8337da5d9f1059935a3092608aefe9a0)

With the original scores the weights are spread over all eight tokens. With the scores multiplied by 100, the token with the largest score takes most of the weight and the rest are close to zero. Under independent zero-mean unit-variance components, the score standard deviation grows as $\sqrt{d_k}$. Scaling controls this growth; it does not guarantee that softmax never saturates.

The [attention scaling](https://aegean.ai/aiml-common/lectures/nlp/transformers/attention-scaling-explained/attention_scaling_explained.md) section derives why $\sqrt{d_k}$ is the right factor, with a variance analysis and experiments.

The code for scaled dot-product attention is short. It works on batched queries and keys of shape $B \times T \times d_k$ and values of shape $B \times T \times d_v$. The optional mask is covered next.

> [accordion] Code
>
> ```python theme={null}
> def scaled_dot_product_attention(query, key, value, mask=None):
>     dim_k = query.size(-1)
>     scores = torch.bmm(query, key.transpose(1, 2)) / math.sqrt(dim_k)
>     if mask is not None:
>         scores = scores.masked_fill(mask == 0, float("-inf"))
>     weights = F.softmax(scores, dim=-1)
>     return torch.bmm(weights, value), weights
>
>
> out, weights = scaled_dot_product_attention(Q[None], K[None], V[None])
> print("output:", tuple(out.shape), " weights:", tuple(weights.shape))
> ```

```output theme={null}
output: (1, 8, 4)  weights: (1, 8, 8)
```

### Masking and causal attention

A decoder generates one token at a time, so at inference a token never sees the tokens after it. During next-token training, the output at position $i$ predicts token $i+1$, and may see the input token at position $i$. Training has to respect this constraint. Otherwise the model would learn to use future tokens, which are ground truth that is not available during inference.

To prevent this, we *mask* the scores of the future tokens by setting them to $-\infty$ before the softmax. The softmax output is then exactly 0 for those tokens. For query $q_i$, only keys $k_1$ through $k_i$ are accessible, and every key $k_j$ with $j > i$ is masked. For four tokens the following matrix shows the masking pattern (the factor $1/\sqrt{d_k}$ on finite scores is omitted for readability)

$$
\begin{array}{c|cccc}
 & k_1 & k_2 & k_3 & k_4 \\
\hline
q_1 & q_1 k_1^T & -\infty & -\infty & -\infty \\
q_2 & q_2 k_1^T & q_2 k_2^T & -\infty & -\infty \\
q_3 & q_3 k_1^T & q_3 k_2^T & q_3 k_3^T & -\infty \\
q_4 & q_4 k_1^T & q_4 k_2^T & q_4 k_3^T & q_4 k_4^T
\end{array}
$$

The mask is a lower-triangular matrix of ones. The next cell applies it to the 8-token context and compares the result with PyTorch's built-in causal attention.

> [accordion] Code
>
> ```python theme={null}
> mask = torch.tril(torch.ones(T, T))
> out, weights = scaled_dot_product_attention(Q[None], K[None], V[None], mask=mask)
> print("causal attention weights:\n", weights[0])
>
> reference = F.scaled_dot_product_attention(Q[None], K[None], V[None], is_causal=True)
> print("matches F.scaled_dot_product_attention:", torch.allclose(out, reference, atol=1e-6))
> ```

```output theme={null}
causal attention weights:
 tensor([[1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
        [0.53, 0.47, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
        [0.44, 0.28, 0.28, 0.00, 0.00, 0.00, 0.00, 0.00],
        [0.32, 0.38, 0.09, 0.22, 0.00, 0.00, 0.00, 0.00],
        [0.22, 0.13, 0.14, 0.38, 0.13, 0.00, 0.00, 0.00],
        [0.19, 0.28, 0.16, 0.10, 0.16, 0.11, 0.00, 0.00],
        [0.07, 0.12, 0.12, 0.07, 0.19, 0.05, 0.38, 0.00],
        [0.11, 0.11, 0.14, 0.09, 0.14, 0.13, 0.15, 0.13]])
matches F.scaled_dot_product_attention: True
```

The first token can only attend to itself, so its row is a single 1. Every row still sums to 1, and every entry above the diagonal is 0.

### Softmax

The scores can be positive or negative. As in the simple mechanism, a softmax applied to each row, over the keys $j$ of each query $i$, turns them into the attention weights $\alpha_{ij}$. This is the `dim=-1` in the code above.

## Weighting the values

### The value transformation

The query and key transformations allow us to determine which tokens contain information relevant to the token we are contextualizing. However, identifying a relevant token does not imply that all the information contained in its embedding is equally useful.

Consider the sentence "I love bears." Suppose that the query and key transformations establish a strong compatibility between `bears` and `love`. The embedding of `love` may contain information about tense, grammatical function, affection, preference and other semantic properties acquired during training.

Which of these features should participate in the construction of a contextualized representation?

Without a value transformation, the attention mechanism would compute a weighted average of the original embeddings:

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

Notice that the attention weight $\alpha_{ij}$ is a scalar. It controls the contribution of the entire embedding $x_j$, but cannot selectively amplify, suppress or combine its individual features.

We therefore introduce a third linear transformation,

$$
v_j = x_j W^v,
$$

which allows the model to construct a new set of features specifically for information exchange between tokens. The values live in a $d_v$-dimensional space. Nothing requires $d_v = d_k$, but the two are usually equal. The contextualized representation becomes

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

The query and key transformations learn features useful for establishing linguistic relationships, whereas the value transformation learns features useful for exploiting those relationships.

For example, an attention head may establish a relationship between a noun and its governing verb. Another head may establish a relationship between a noun and its modifier. These two relationships may require different kinds of information to be extracted from the same token embedding.

This gives us three complementary feature transformations:

* $W^q$ extracts features useful for identifying contextual needs.
* $W^k$ extracts features useful for determining contextual relevance.
* $W^v$ extracts features useful for constructing contextual representations.

All three transformations are learned jointly during training.

### A mathematical observation

Let $A$ be the $T \times T$ matrix of attention weights $\alpha_{ij}$. Since the value transformation is linear and shared across token positions, we can also write

$$
\begin{aligned}
\hat X &= AV \\
&= A(XW^v) \\
&= (AX)W^v.
\end{aligned}
$$

Attention therefore performs two different operations:

* Left multiplication by $A$ mixes information across tokens.
* Right multiplication by $W^v$ mixes information across feature dimensions.

These two operations act along different axes of the input matrix $X \in \mathbb{R}^{T \times d}$. Attention determines how information flows between tokens, while the value transformation determines the feature representation in which that information is exchanged.

The separation matters most in multi-head attention, where each head learns not only a different pattern of linguistic relationships but also a different feature transformation of the information exchanged through those relationships.

For a single attention head, however, $W^v$ is not strictly necessary to implement contextual information exchange. Its justification is the additional flexibility in learning feature representations. Indeed, in purely linear single-head attention with an output projection, the value and output projection matrices can be combined. It is in multi-head attention that the head-specific value transformations acquire particular architectural significance.

As an example, take the context "The hiking trail led us through *bear* country". Suppose the query of `country` assigns a large weight to the key of `bear`. The value of `bear` then contributes to the output of `country`. That contribution is a learned vector, not necessarily an explicit representation of an animal or a noun. The residual connection and subsequent layers further transform the representation.

![Block diagram of a single self-attention head: X is projected by W^q, W^k and W^v into Q, K and V; Q times K transpose gives the T by T scores, which are divided by the square root of d\_k, optionally masked, and passed through a row-wise softmax to give the weights A; A times V gives the output](https://mintcdn.com/aegeanaiinc/Yrt_S4TWwKs8h38s/aiml-common/lectures/nlp/transformers/singlehead-self-attention/images/single-head-attention.svg?fit=max\&auto=format\&n=Yrt_S4TWwKs8h38s\&q=85\&s=756d1f7841bb52c05fcc4a1b8e2fdf23)

*A single self-attention head. The causal mask applies only in a decoder.*

The full equation of scaled dot-product self-attention is

$$
\hat X = \mathtt{Attention}(Q, K, V) = \mathtt{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V,
$$

and the output has dimensions $T \times d_v$, where $T$ is the number of tokens in the input sequence and $d_v$ is the dimension of the values. With batching, every tensor gets a leading batch dimension.

> [!WARNING]
>
> Self-attention differs from a dense layer in where its weights come from. If a dense layer learns a very small weight for an input, it applies that weight to every example fed into the layer. In self-attention, a very small attention weight comes from the specific tokens present in that input, and a different input gives different weights.

## Example: contextual representations in BERT

We now return to the motivating example using a pretrained bidirectional encoder. Compare "I love bears", "She bears the pain" and "Bears won the game". The uncased BERT tokenizer maps `bears` to the same ID in all three sentences, and the code checks this. The token sits at a different position in each sentence, so its input embeddings already differ through the position embedding. We compare its hidden states across layers; these include attention, residual connections, normalization and feed-forward transformations.

> [accordion] Code
>
> ```python theme={null}
> import warnings
>
> warnings.filterwarnings("ignore", message="IProgress not found")
>
> from transformers import AutoModel, AutoTokenizer
> from transformers.utils import logging
>
> logging.set_verbosity_error()  # hide the weight-loading report
> logging.disable_progress_bar()
>
> checkpoint = "bert-base-uncased"
> tokenizer = AutoTokenizer.from_pretrained(checkpoint)
> model = AutoModel.from_pretrained(
>     checkpoint, output_attentions=True, output_hidden_states=True, attn_implementation="eager"
> ).eval()
>
> sentences = ["I love bears", "She bears the pain", "Bears won the game"]
> runs = []
> for sentence in sentences:
>     inputs = tokenizer(sentence, return_tensors="pt")
>     with torch.no_grad():
>         output = model(**inputs)
>     tokens = tokenizer.convert_ids_to_tokens(inputs.input_ids[0])
>     i = tokens.index("bears")
>     runs.append({
>         "tokens": tokens,
>         "position": i,
>         "token_id": inputs.input_ids[0, i].item(),
>         # embedding of "bears": input embedding, then after each layer
>         "embedding": torch.stack([h[0, i] for h in output.hidden_states]),
>         # attention weights of "bears", averaged over the 12 heads of each layer
>         "attention": torch.stack([a[0, :, i].mean(dim=0) for a in output.attentions]),
>     })
>     print(tokens, "-> 'bears' at position", i)
>
> assert len({r["token_id"] for r in runs}) == 1
> pairs = [(0, 1), (0, 2), (1, 2)]
> similarities = [F.cosine_similarity(runs[a]["embedding"], runs[b]["embedding"], dim=-1) for a,b in pairs]
> ```

```output theme={null}
['[CLS]', 'i', 'love', 'bears', '[SEP]'] -> 'bears' at position 3
```

```output theme={null}
['[CLS]', 'she', 'bears', 'the', 'pain', '[SEP]'] -> 'bears' at position 2
```

```output theme={null}
['[CLS]', 'bears', 'won', 'the', 'game', '[SEP]'] -> 'bears' at position 1
```

![Output from cell 12](https://mintcdn.com/aegeanaiinc/0ApiccrGMnyvyrYq/aiml-common/lectures/nlp/transformers/singlehead-self-attention/images/cell_12_output_1.svg?fit=max\&auto=format\&n=0ApiccrGMnyvyrYq\&q=85\&s=5ca9e6aac854ae9be3e7423aeb605e54)

At the input the three representations differ only through the position embedding, so their similarity starts between 0.93 and 0.97. Differences in later layers demonstrate contextualization, not proof that a specific semantic sense has been isolated. Similarity need not decrease monotonically. The next figure shows attention weights averaged across heads; these are not a measure of causal importance.

![Output from cell 13](https://mintcdn.com/aegeanaiinc/0ApiccrGMnyvyrYq/aiml-common/lectures/nlp/transformers/singlehead-self-attention/images/cell_13_output_1.svg?fit=max\&auto=format\&n=0ApiccrGMnyvyrYq\&q=85\&s=f8334323fccf19b7445bc2e2ab48d42e)

Inspect the maps for differences across contexts and layers. Averaging heads can hide distinct patterns; a large weight on a special token does not by itself establish its importance.

## 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.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. |

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

## References

* 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)
* 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/singlehead-self-attention).


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