HSR Sector 6 · Bangalore +91 96110 27980 Mon–Sat · 09:30–20:30
Chapter 10 of 25 — Generative AI Fundamentals
advanced Chapter 10 of 25

Multi-Head Attention and Positional Encoding in Transformers

By Vikas Swami, CCIE #22239 | Updated Mar 2026 | Free Course

What are multi head attention and positional encoding?

Multi head attention lets a Transformer compute several weighted mixtures of token information in parallel, using a different set of query, key, and value projections for each head. Positional encoding gives attention access to token order, either by modifying input embeddings, rotating queries and keys, or adjusting attention scores, depending on the architecture.

Consider “the server contacts the client” and “the client contacts the server.” Both sequences contain the same tokens, but the order changes who initiates the connection. A model needs a way to distinguish those roles. It also needs a way to move useful information between token positions, such as carrying the subject into the representation of the verb. Position signals help with the first task. Attention performs the second by mixing information across positions.

In the Transformer architecture, attention is a sublayer alongside a feed-forward network and is used with residual connections and normalisation. This chapter isolates the attention computation and then shows where position enters it. Keep two axes separate: the sequence axis identifies tokens, while the feature axis contains the coordinates of each token's representation.

How does scaled dot-product self-attention work?

In self-attention, queries, keys, and values are projected from the same sequence representation X. For one head, Q = XW_Q, K = XW_K, and V = XW_V. A query determines which keys score highly, and the corresponding values are the vectors that get mixed. Query and key widths must match for the dot product. Value width can differ. The attention mechanism chapter introduces these roles in more detail.

For a sequence of length T, the score matrix QK^T has shape (T, T). Entry (i, j) is the dot product of the query at position i and the key at position j. With an additive mask M, the calculation is A = softmax(QK^T / sqrt(d_k) + M) and Z = AV. Apply softmax across keys within each query row. Each row of Z is therefore a weighted sum of value vectors, with nonnegative weights that sum to one if the row has at least one valid key.

Why divide by sqrt(d_k)? Under the simple assumption that query and key coordinates are independent, zero-mean, and unit-variance, each product has variance one. Summing d_k such terms gives variance d_k, so dividing by its square root returns the variance to one. Learned activations need not match these assumptions. The argument explains why the scale controls the typical growth of logits with head width. Without scaling, large logit gaps can push softmax close to a one-hot distribution and make gradients through it small.

Which tokens can contribute depends on the mask. In full bidirectional self-attention, a token can attend to all valid tokens, including itself. In causal self-attention, query i can attend only to positions j <= i. A padding mask separately excludes padding keys. In the additive form, an allowed entry is zero and a blocked entry is negative infinity, applied before softmax. A fully blocked row needs explicit handling: ordinary softmax on a row of negative infinities is undefined. Attention provides a direct path between distant allowed tokens, but the model still has to learn to use that path.

How does multi head attention combine parallel heads?

For head r, learn a separate set of matrices W_Q^r, W_K^r, and W_V^r. These define the coordinates in which that head scores token pairs and the value features that it passes forward. One head might put substantial weight on a nearby token, while another uses a distant occurrence of the same identifier. This is a possible learned pattern, not an assignment made by the architecture. Heads can overlap, and a high attention weight alone does not establish how much a token affected the final prediction.

One token matrix feeds parallel attention heads whose output features are concatenated and projected into the model width.
Each head computes its own weighted sum of values before the output projection mixes features across heads.

Using a batched implementation, let B be batch size, H be head count, and d_model be the model width. The following shapes assume the common choice D = d_model / H for both query/key width and value width.

StageShapeWhat changes
Input(B, T, d_model)One feature vector per token
Queries, keys, and values(B, H, T, D) eachLinear projections create separate features for each head
Attention logits or weights(B, H, T, T)One query-by-key matrix per sequence and head
Weighted values(B, H, T, D)Each query gets one mixed value vector per head
Concatenated features(B, T, H * D)Head outputs join along the feature axis
Projected output(B, T, d_model)W_O mixes feature coordinates across heads at each token

The output is Concat(Z^1, ..., Z^H) W_O. Concatenation preserves all T token rows. The output projection acts on each row independently, so it does not perform another round of token mixing. Implementations can compute all three projections with a single linear layer of output width 3 * d_model and reshape the result into heads. This is equivalent to storing the individual projection matrices in one packed matrix.

Holding d_model fixed while increasing H makes each head narrower. Under these width assumptions, the main query-key and attention-value multiplications together cost O(B * T^2 * d_model) for dense attention. However, explicitly storing every score can require B * H * T^2 entries. That difference matters for long context windows. Fused attention kernels can avoid materialising the entire score matrix in device memory, though dense attention still evaluates a quadratic number of token pairs.

Worked example: How do two attention heads process two tokens?

Take two input rows, X = [[1, 0], [0, 2]], and use two heads of width one. For head 1, let each projection select the first coordinate. For head 2, let each select the second coordinate. These are chosen weights for arithmetic practice. There is no mask, and the scaling factor is sqrt(1) = 1.

  1. Head 1: Q = K = V = [[1], [0]]. The score rows are [1, 0] and [0, 0]. Their softmax weights are approximately [0.731, 0.269] and [0.5, 0.5]. Multiplying each row by the values gives Z^1 = [[0.731], [0.5]].
  2. Head 2: Q = K = V = [[0], [2]]. The score rows are [0, 0] and [0, 4]. Their weights are approximately [0.5, 0.5] and [0.018, 0.982]. The outputs are Z^2 = [[1], [1.964]].
  3. Concatenate and project: The feature rows are now [0.731, 1] and [0.5, 1.964]. Use W_O = [[1, 1], [1, -1]] to map a row [a, b] to [a + b, a - b]. The final output rows are approximately [1.731, -0.269] and [2.464, -1.464].

For a quick check, apply a causal mask to the same example. The first query can see only the first key, so its weight row becomes [1, 0] in both heads. Its concatenated value becomes [1, 0] and its projected output becomes [1, 1]. The second query still sees both positions, so its result stays the same. This isolates the mask's effect without changing any learned weights.

How does sinusoidal positional encoding work?

With no position-dependent inputs or mask, self-attention is permutation equivariant: shuffle the token rows and the output rows follow the same shuffle. To see why, write the row shuffle as a permutation matrix P. The score matrix becomes P(QK^T)P^T; softmax permutes its rows and columns accordingly. The values become PV, so the final result is PZ. A causal mask imposes an order-dependent visibility pattern and breaks this unrestricted symmetry. It still does not explicitly encode how far apart any two allowed positions are.

Four token embeddings are each added coordinate by coordinate to a same-width positional vector before entering a Transformer block.
Absolute sinusoidal encoding adds a different position vector to the embedding at each sequence index.

The original Transformer adds a fixed vector PE(p) to each input token's embedding. For an even model width and zero-based position p, pair coordinate 2i with 2i + 1. Define w_i = 1 / 10000^(2i / d_model). Then PE(p, 2i) = sin(p * w_i) and PE(p, 2i + 1) = cos(p * w_i). The input row is the element-wise sum E(token_p) + PE(p), so its width stays d_model. In the original architecture the embedding is scaled by sqrt(d_model) before this addition.

For d_model = 4, the angular frequencies are 1 and 0.01 radians per position. At p = 0, the position vector is [0, 1, 0, 1]. At p = 1, it is approximately [0.84147, 0.54030, 0.01000, 0.99995]. Adding the second vector to the illustrative embedding [0.2, -0.1, 0.3, 0.4], without embedding scaling for this calculation, gives [1.04147, 0.44030, 0.31000, 1.39995]. The first pair changes faster across neighbouring positions than the second pair.

For any fixed offset k, the angle addition identities express the sine and cosine pair at p + k as a linear transformation of the pair at p, with coefficients depending only on k * w_i. Also, the dot product between the two position vectors at p and q is sum_i cos((p - q) * w_i). The positional vectors therefore contain a direct mathematical signal about relative displacement. Actual attention logits also involve token embeddings and learned projections, so the model does not automatically implement a fixed rule for distance.

How do sinusoidal encoding, RoPE, and ALiBi differ?

“Position” can enter at different stages of attention. When reading a checkpoint's configuration, check where its position method is applied before changing maximum length, padding, or cache behaviour. Two methods that both use sine and cosine may apply them to different tensors.

MethodWhere it entersWhat it changesLength consideration
Fixed sinusoidal encodingInput embeddingsAdds a fixed vector for each absolute positionVectors are computable at new indices, but model quality can drop outside the training range
Learned absolute embeddingsInput embeddingsAdds a trainable vector looked up by position indexIndices beyond the table need a strategy such as extension or interpolation
Rotary positional embedding (RoPE)Queries and keysRotates coordinate pairs as a function of positionPhases at longer lengths may be unfamiliar to the model; scaling variants change the frequency schedule
Attention with Linear Biases (ALiBi)Attention logitsIn causal attention, subtracts a head-specific slope times distance for each allowed keyThe bias is defined at new distances, though that alone does not establish long-context quality

For RoPE, let R(p) be the block-diagonal rotation at position p, acting on pairs of query or key coordinates. The rotated dot product is (R(p)q)^T(R(s)k) = q^T R(s - p) k. The equality follows because transposing a rotation reverses its angle and composing rotations adds their angles within each coordinate pair. Thus the rotation contribution depends on relative displacement, while the score still depends on query and key content. Standard RoPE leaves values unrotated. During cached decoding, a new query must use a position index on the same scale and timeline as the cached keys.

With causal ALiBi, the unmasked logit for head r becomes q_i · k_j / sqrt(D) - m_r * (i - j) for j <= i, with positive slope m_r. A larger slope penalises distant keys more strongly. It does not forbid attention to those keys if their content scores offset the penalty. RoPE changes the content-dependent dot product itself, so a larger distance does not necessarily reduce a RoPE logit.

How do you implement multi head attention in PyTorch?

The following example combines fixed sinusoidal positions with causal self-attention. It computes the intermediate weights explicitly so you can inspect them, then checks the pre-projection head outputs against PyTorch's scaled dot-product attention operator. The input batch contains sequences of equal length with no padding. The module omits dropout, residual connections, and normalisation to keep the calculation visible.

import math
import torch
from torch import nn
from torch.nn import functional as F


def sinusoidal_positions(length, width, device):
    if width % 2:
        raise ValueError("Use an even embedding width")
    pos = torch.arange(length, device=device, dtype=torch.float32)
    even = torch.arange(0, width, 2, device=device, dtype=torch.float32)
    freq = torch.exp(-math.log(10000.0) * even / width)
    phase = pos[:, None] * freq[None, :]
    return torch.stack((phase.sin(), phase.cos()), dim=-1).flatten(1)


class MultiHeadSelfAttention(nn.Module):
    def __init__(self, width, heads):
        super().__init__()
        if heads <= 0 or width % heads:
            raise ValueError("Width must split evenly across heads")
        self.heads = heads
        self.head_dim = width // heads
        self.qkv = nn.Linear(width, 3 * width, bias=False)
        self.out = nn.Linear(width, width, bias=False)

    def forward(self, x):
        batch, length, width = x.shape
        packed = self.qkv(x).reshape(
            batch, length, 3, self.heads, self.head_dim
        )
        q, k, v = packed.permute(2, 0, 3, 1, 4).unbind(0)
        scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)

        future = torch.ones(
            length, length, device=x.device, dtype=torch.bool
        ).triu(diagonal=1)
        weights = scores.masked_fill(future, float("-inf")).softmax(dim=-1)
        heads_out = weights @ v

        reference = F.scaled_dot_product_attention(
            q, k, v, is_causal=True, dropout_p=0.0
        )
        torch.testing.assert_close(heads_out, reference)

        merged = heads_out.transpose(1, 2).reshape(batch, length, width)
        return self.out(merged), weights


torch.manual_seed(7)
ids = torch.tensor([[3, 8, 3, 1], [2, 4, 5, 9]])
embedding = nn.Embedding(10, 8)
tokens = embedding(ids)
pe = sinusoidal_positions(ids.shape[1], tokens.shape[-1], tokens.device)
x = tokens + pe.to(tokens.dtype).unsqueeze(0)
output, weights = MultiHeadSelfAttention(width=8, heads=2)(x)
assert output.shape == (2, 4, 8)
assert weights.shape == (2, 2, 4, 4)
assert torch.count_nonzero(weights.triu(diagonal=1)).item() == 0

Read weights[0, 1, 2, :] as the distribution over keys for batch item zero, head one, and query two. Its last entry must be zero because key three lies in the future. Token ID 3 appears twice in the first sequence: both copies start from the same embedding lookup, but their input rows differ after position addition. As a follow-up test, change only the final token ID and verify that the first three output rows stay unchanged with the same model weights.

When moving this implementation into a training loop, remove the reference assertion and use the fused operator directly where supported. Explicit weights are useful for inspection, but the example materialises a full score matrix and computes attention twice. If you add padding, read the mask convention of the exact API. In this example, True means block because it is passed to masked_fill. For a Boolean attn_mask passed directly to scaled_dot_product_attention, True means the entry may participate. Handle padded query outputs separately so they do not affect the loss.

Key Takeaways

  • Self-attention compares queries with keys, normalises each query row over allowed keys, and uses the resulting weights to mix values.
  • Dividing logits by sqrt(d_k) controls their scale as query and key width grows.
  • Each head has its own projections. Concatenation joins head features, and the output projection mixes those features at each token.
  • Causal masking determines visibility; a positional method supplies an additional signal tied to index or distance.
  • Sinusoidal encoding adds fixed input vectors, RoPE rotates queries and keys, and ALiBi adjusts logits with a distance penalty.
  • Use small shape checks and a causal invariance test before optimising attention or adding padding and caching.

Frequently Asked Questions

Does each attention head learn one specific relationship?

No. Heads have independent projection weights, but training usually gives them no explicit roles. A head can behave differently across examples or layers, and several heads may learn similar patterns. To test whether a particular head matters for a task, measure how removing or altering its output changes performance on held-out examples.

Why does softmax run across keys rather than queries?

Each query needs its own distribution over the values it can read. Normalising across keys gives each query row a sum of one and lets it choose a different mixture. Normalising across queries would instead constrain how a key distributes weight among query positions, which is a different computation.

Does a causal mask remove the need for positional encoding?

A causal mask gives positions different visible prefixes, so it already introduces order-dependent structure. However, a standard mask treats all allowed keys the same at the masking step. It does not directly distinguish a key one position back from one ten positions back. Positional methods give the network another way to represent that difference.

Does increasing the number of heads always improve attention?

No. At fixed model width, adding heads shrinks each head's feature space. It also increases the number of score matrices in an implementation that materialises them. The best choice depends on what the model learns, which head dimensions the hardware handles efficiently, and how the trained model performs on representative validation data.

Can RoPE or sinusoidal encoding handle an unlimited context window?

Both define position signals at indices beyond those seen in training, but being able to compute those signals does not imply reliable predictions there. Training lengths, numerical precision, available memory, and the attention implementation impose practical limits. Evaluate at the intended lengths with tasks that require information from distant parts of the input.

Ready to Master Generative AI Fundamentals?

Join 45,000+ students at Networkers Home. CCIE-certified trainers, 24x7 real lab access, and Placement Guarantee* — structured interview support until placed.

Explore Course