🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Transformer Architecture: Self-Attention and Beyond

Natural Language ProcessingTransformer Architecture: Self-Attention and BeyondđŸŸĸ Free Lesson

Transformer Architecture: Self-Attention and Beyond

What You'll Learn

  • 1Derive scaled dot-product attention and explain the square root scaling
  • 2Explain why multiple heads are concatenated instead of averaged
  • 3Write the sinusoidal positional encoding and its relative shift property
  • 4Count parameters and FLOPs for a stacked transformer block

Attention with recurrence needed one step per token, so Vaswani et al. (2017) removed recurrence and let every position attend to every other position in a single pass. This lesson derives the scaled dot-product score, the multi-head decomposition, the sinusoidal position signals, and the residual plus normalization scheme that keeps 6 to 96 stacked layers trainable, then counts what one layer actually costs.

Scaled Dot-Product Attention

Queries, keys, and values are matrices produced by learned projections of the input, and attention mixes the values in proportion to how well each query matches each key:

If query and key entries are independent with unit variance, their dot product has variance , so large pushes the softmax into its saturated corners and the gradients vanish. Dividing by recenters the scores near zero, where the softmax is steepest.

Padding and look-ahead are handled by adding a large negative constant to masked positions before the softmax, which sends their weight to zero without changing the normalization of the rest.

Multi-Head Attention

Running one attention with full width mixes every relation type into one score, so the transformer runs smaller attentions in parallel:

Each head uses , for example 512 divided by 8 equals 64, so the total compute stays close to a single full-width run while the model can dedicate heads to syntax, coreference, and position patterns. The heads are concatenated along the feature axis and projected back:

Self-attention sets from the same sequence, while cross-attention uses decoder queries against encoder keys and values, which is how a translation decoder reads the source.

Positional Encoding and Normalization

Recurrence gave a natural order, so the transformer injects position as a fixed signal added to the embeddings:

Sine and cosine of a fixed offset are linear functions of each other, so a relative shift can be represented as a rotation, which lets the model extrapolate to longer sequences than it saw in training. Each block then adds a residual path and normalizes:

ModelLayersHeadsParameters
Transformer base6 encoder, 6 decoder5128about 65 million
Transformer big6 encoder, 6 decoder102416about 213 million
BERT-base12 encoder76812110 million
GPT-396 decoder1228896175 billion

Worked Examples

Worked Code

python
import numpy as np

def softmax(x, axis=-1):
    e = np.exp(x - x.max(axis=axis, keepdims=True))
    return e / e.sum(axis=axis, keepdims=True)

def scaled_dot_product_attention(Q, K, V, mask=None):
    d_k = Q.shape[-1]
    scores = Q @ np.swapaxes(K, -1, -2) / np.sqrt(d_k)
    if mask is not None:
        scores = np.where(mask, scores, -1e9)
    weights = softmax(scores, axis=-1)
    return weights @ V, weights

def multi_head(Q, K, V, h):
    d = Q.shape[-1]
    dk = d // h
    heads, weights = [], []
    rng = np.random.default_rng(0)
    for _ in range(h):
        Wq, Wk, Wv = (rng.normal(size=(d, dk)) * 0.05 for _ in range(3))
        out, w = scaled_dot_product_attention(Q @ Wq, K @ Wk, V @ Wv)
        heads.append(out)
        weights.append(w)
    return np.concatenate(heads, axis=-1), weights

seq, d = 6, 8
X = np.random.default_rng(1).normal(size=(seq, d))
out, weights = multi_head(X, X, X, h=4)
print("output shape:", out.shape, "head weight sum:", weights[0][0].sum().round(3))
python
import math
import torch
import torch.nn as nn

def sinusoidal_encoding(length, d_model):
    pos = torch.arange(length).unsqueeze(1).float()
    div = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
    pe = torch.zeros(length, d_model)
    pe[:, 0::2] = torch.sin(pos * div)
    pe[:, 1::2] = torch.cos(pos * div[:pe[:, 1::2].shape[1]])
    return pe

class TransformerBlock(nn.Module):
    def __init__(self, d_model=512, heads=8, d_ff=2048, dropout=0.1):
        super().__init__()
        self.attn = nn.MultiheadAttention(d_model, heads, batch_first=True)
        self.ff = nn.Sequential(nn.Linear(d_model, d_ff), nn.GELU(),
                                nn.Linear(d_ff, d_model))
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.drop = nn.Dropout(dropout)

    def forward(self, x, mask=None):
        attn_out, _ = self.attn(x, x, x, attn_mask=mask)
        x = self.norm1(x + self.drop(attn_out))
        return self.norm2(x + self.drop(self.ff(x)))

block = TransformerBlock(d_model=512, heads=8)
print("params:", sum(p.numel() for p in block.parameters()))

Real-World Applications

  • Machine translation: the original 65 million parameter base model reached 27.3 BLEU on WMT 2014 English to German with a fraction of the training time of recurrent systems.
  • Long documents: sliding window and sparse attention variants reuse the same score equation over chunks, which is how 100,000 token contexts became practical.
  • Vision and audio: patches or spectrogram frames enter the identical block, because the equations only assume a sequence of vectors.

💡One equation covers encoder and decoder

Self-attention sets Q, K, and V from the same sequence, cross-attention reads encoder states with decoder queries, and masked attention blocks future positions, so a single scaled dot-product routine implements all three roles.

Common Mistakes

Forgetting the square root scaling

Fix: At d_k = 64 the raw scores saturate the softmax and half the heads stop learning.

Applying layer norm before the residual add

Fix: Use pre-norm or post-norm consistently, mixing them changes gradient scale per layer.

Averaging heads instead of concatenating

Fix: Concatenation followed by W_O lets the model mix heads; averaging throws away capacity.

Best Practices

  • Keep one positional encoding convention per model, since mixing learned and sinusoidal signals breaks extrapolation
  • Warm up the learning rate over four thousand steps so attention logits stay in the unsaturated range
  • Mask padding with a large negative constant before the softmax, never after

Key Takeaways

  • Dot product scores have variance d_k, so the divide by square root d_k keeps the softmax steep
  • h heads of width d_model divided by h cost about the same as one wide attention while separating relation types
  • Sinusoidal positions encode relative offsets as rotations, which is why extrapolation works
  • A base layer is 4d squared plus 2d times d_ff parameters, about 3.15 million at d = 512

Frequently Asked Questions

Why not use a single attention head with full width?

A single head must produce one score per key pair, so all relation types compete for one number. Eight heads of width 64 give eight independent scores for the same pair, and the output projection learns which head to trust for which context.

What happens when the input exceeds the training length?

Sinusoidal codes for unseen positions are still well defined, but the model rarely learned to use them, so quality degrades past the trained length. Rotary embeddings and relative position biases were introduced to make the extrapolation smoother.

Why are residual connections required?

Each block only has to learn a delta on the residual stream, so the gradient path from the loss to layer one is a straight sum rather than a product of many Jacobians, and training 96 layers stays stable.

Interview Questions

Q1: Why divide by the square root of d_k rather than d_k?

The dot product standard deviation grows with the square root of d_k, so dividing by that same root returns the scores to unit variance where the softmax still has gradient.

Q2: What does the output projection W_O contribute?

It mixes the concatenated heads back into one residual update, so information can flow between heads instead of each head writing its own slice.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement