Transformer blocks, residual connections and positional information
What it is
A Transformer stacks blocks containing multi-head self-attention and a position-wise MLP, each wrapped in residual connections and normalization. Attention lets tokens exchange information; the MLP then transforms each token independently using its newly contextualised representation. Residual additions preserve the incoming representation beside the block's new contribution, while normalization keeps layer scales manageable. Positional embeddings or encodings supply order because attention alone is permutation-invariant; an unpositioned model sees the same set of token vectors regardless of order.
Why it matters
Residual paths preserve an easy route for signals and gradients through many layers; position is what lets the model distinguish 'dog bites man' from the reverse. This repeated block structure also makes Transformer configuration legible: depth sets how often contextualisation is refined, width sets representation capacity, head count divides attention into multiple subspaces, and context length sets the available evidence and computational bill.
In the real world: The repeating unit behind ChatGPT-style assistants, modern search engines and code assistants.
Visual example
Deep learningResidual paths wrap the two transformations repeated at every depth.
import torch
import torch.nn as nn
layer = nn.TransformerEncoderLayer(
d_model=512, nhead=8, dim_feedforward=2048,
batch_first=True, norm_first=True, # pre-norm
)
encoder = nn.TransformerEncoder(layer, num_layers=6)
encoder(torch.randn(4, 20, 512)).shape # (4, 20, 512)Assuming multi-head attention means multiple independent models. Heads are smaller learned projections trained jointly, and their usefulness depends on the whole block around them.