"Attention Is All You Need" (2017)
In June 2017 Vaswani et al. published a paper at Google Brain that would reshape the entire field of deep learning. The title was deliberately provocative: Attention Is All You Need. The core claim was that a model built entirely from attention mechanisms — with no recurrence and no convolutions — could outperform every existing sequence-to-sequence architecture on machine translation benchmarks.
They were right. The architecture they introduced, the Transformer, not only matched the best RNN and CNN-based translation systems but surpassed them while training significantly faster. Within two years, the Transformer became the foundation of BERT, GPT, T5, and virtually every breakthrough in natural language processing. Today it has expanded into computer vision, protein folding, weather forecasting, and — increasingly — civil engineering applications.
The key innovations were not individual components but their composition. Self-attention (which we explored in Sub-chapter 5.2) was already known. Residual connections and layer normalisation had been used in deep CNNs. The breakthrough was assembling these pieces into a coherent, elegant architecture that eliminated the sequential bottleneck of RNNs entirely.
This sub-chapter assumes you understand the attention mechanism from Sub-chapter 5.2: Query, Key, and Value vectors, scaled dot-product attention, and self-attention. We build directly on those foundations to construct the full Transformer.
Why the Transformer Matters for Civil Engineers
The Transformer is relevant to civil engineering not because you will build one from scratch, but because it is the engine inside the AI tools you will increasingly use: automated specification analysis, generative design assistants, sensor anomaly detection systems, and natural-language interfaces to BIM models. Understanding the architecture lets you evaluate these tools critically — knowing their strengths, limitations, and failure modes.
The Design Review Committee Analogy
The Transformer is a multi-disciplinary design review committee. Imagine a major infrastructure project — a cable-stayed bridge — undergoing its final design review. The review committee has eight specialist engineers (the attention heads), each focusing on a different aspect:
- Head 1 (Structural): focuses on load paths, member forces, and connection details
- Head 2 (Geotechnical): focuses on foundation bearing capacity and settlement
- Head 3 (Hydraulic): focuses on scour depth and flood levels
- Head 4 (Seismic): focuses on dynamic response and ductility
- Head 5 (Durability): focuses on concrete cover, coatings, and corrosion protection
- Head 6 (Construction): focuses on build sequence, crane access, and temporary works
- Head 7 (Cost): focuses on material quantities, labour hours, and budget
- Head 8 (Compliance): focuses on code references, design standards, and regulatory requirements
Each head reads the same set of design documents (the input sequence) but attends to different sections. After the review, their individual findings are concatenated into a combined report and passed through a synthesis step (the linear projection) that merges all perspectives into a unified assessment.
This happens six times (the encoder layers). At each round, the committee refines its understanding, building on the combined insights from the previous round. Early rounds catch obvious issues; later rounds identify subtle interactions between disciplines — like how the geotechnical settlement affects the structural load distribution which in turn affects the seismic response.
This analogy maps onto every major component of the Transformer: multi-head attention is the committee of specialists, the feed-forward layers are where each specialist processes their findings independently, residual connections ensure that original information is never lost, and layer normalisation keeps the review process stable across rounds.
Multi-Head Attention
In Sub-chapter 5.2 we learned that a single attention head computes Query, Key, and Value projections and produces a weighted combination of Values. A single head, however, can only focus on one type of relationship at a time. Multi-head attention runs h parallel attention heads, each with its own learned Q, K, V projection matrices, so the model can simultaneously attend to information from different representation subspaces.
Multi-Head Attention Formula
MultiHead(Q, K, V) = Concat(head1, ..., headh) · WO
where headi = Attention(Q · WiQ, K · WiK, V · WiV)
Each head operates on a subspace of the full model dimension. If dmodel = 512 and h = 8 heads, each head works with dk = dv = 512/8 = 64 dimensions. The total computation cost is similar to a single head with full dimensionality, but the model gains the ability to attend to multiple relationships simultaneously.
What Different Heads Learn
Research has shown that different attention heads in trained Transformers specialise in recognising different types of relationships:
Observed Head Specialisations
- Positional heads: attend to adjacent tokens (local context)
- Syntactic heads: attend to grammatically related words (subject-verb pairs)
- Semantic heads: attend to contextually related words regardless of distance
- Rare-token heads: disproportionately attend to unusual or important tokens
No one programs these specialisations. They emerge naturally during training as the model discovers that different types of attention patterns are useful for the task.
The original Transformer used dmodel = 512 with h = 8 attention heads. Modern large language models scale both parameters dramatically: GPT-3 uses dmodel = 12288 with 96 heads. The principle, however, remains identical.
Positional Encoding: Why Position Matters
There is a critical problem with self-attention: it is permutation-invariant. If you shuffle the order of input tokens, the attention mechanism produces the same output (just shuffled the same way). Self-attention has no built-in notion of position or order — every token is treated as if it exists in a position-less set.
This is a serious limitation. In an RNN, position is implicit: the hidden state at step 5 has been shaped by steps 1 through 4. But the Transformer processes all positions in parallel with no recurrence, so it has no idea whether a token appears at position 1 or position 100 unless we explicitly tell it.
Positional encoding is like chainage markers on a highway alignment. A set of horizontal curve parameters (radius, deflection angle, superelevation) is meaningless without knowing where along the route each curve occurs. Chainage markers (Km 0+000, Km 1+250, etc.) provide absolute position. Without them, you have a bag of curves with no spatial order — you could not reconstruct the road alignment.
Similarly, positional encodings stamp each token with a unique position signature so the Transformer knows that "beam" at position 3 is different from "beam" at position 47, even though the word embedding is the same.
Sinusoidal Positional Encoding
The original Transformer uses sinusoidal functions to generate positional encodings. For each position pos and each dimension i of the encoding vector:
Sinusoidal Encoding Formulae
PE(pos, 2i) = sin(pos / 100002i/dmodel)
PE(pos, 2i+1) = cos(pos / 100002i/dmodel)
Even dimensions use sine; odd dimensions use cosine. The wavelength increases geometrically from 2π (for i = 0) to 10000 · 2π (for i = dmodel/2). This creates a unique pattern for every position.
Why Sinusoids?
The choice of sinusoidal functions is not arbitrary. The authors chose them for two key properties:
Unique Encoding for Every Position
The combination of sine and cosine waves at different frequencies produces a unique vector for every position. No two positions share the same encoding, so the model can always distinguish between them.
Relative Positions Through Linear Transformations
For any fixed offset k, PE(pos + k) can be expressed as a linear function of PE(pos). This means the model can learn to attend to relative positions (e.g., "two tokens to the left") without needing a separate mechanism. The sinusoidal structure encodes relative distance naturally.
Adding Encodings to Embeddings
The positional encoding vector has the same dimension dmodel as the word embedding. It is added element-wise to the input embedding, not concatenated. This means the model receives a single vector per token that combines both what the token is (the embedding) and where it appears (the positional encoding).
The original paper found that learned positional embeddings performed nearly identically to sinusoidal encodings. Modern models like BERT use learned positional embeddings, while others use more advanced schemes like Rotary Position Embedding (RoPE). The sinusoidal approach remains important conceptually because it generalises to unseen sequence lengths without retraining.
The Encoder Stack
The encoder's job is to process the input sequence and produce a rich, contextualised representation of every token. It does this by stacking N identical layers (N = 6 in the original paper). Each layer contains two sub-layers:
Sub-layer 1: Multi-Head Self-Attention
Every token attends to every other token in the input sequence (including itself). This is the self-attention mechanism from Sub-chapter 5.2, extended to multiple heads. After this sub-layer, each token's representation has been enriched with contextual information from the entire sequence.
Sub-layer 2: Position-wise Feed-Forward Network
After attention has mixed information across positions, each position passes through a two-layer feed-forward network independently. The same feed-forward network is applied to every position, but there is no information exchange between positions in this sub-layer.
FFN(x) = max(0, x · W1 + b1) · W2 + b2
The inner dimension dff is typically 4 × dmodel (2048 for dmodel = 512). The ReLU activation introduces non-linearity, allowing the model to learn complex transformations of the attended representations.
Residual Connections
Each sub-layer is wrapped in a residual connection (also called a skip connection). The output of each sub-layer is:
Residual Connection Formula
output = LayerNorm(x + SubLayer(x))
The input x is added directly to the sub-layer's output before normalisation. This means the sub-layer only needs to learn the residual — the difference between the desired output and the input — rather than the full transformation. This makes deep networks dramatically easier to train.
Residual connections are like redline markups on design drawings. When a reviewer marks up a structural drawing, they do not redraw the entire sheet. They add annotations, circles, and corrections on top of the original drawing. The original information is fully preserved (the base drawing), and the markup adds incremental changes (the residual). If a reviewer adds nothing useful, the original drawing passes through unchanged — no information is lost.
Layer Normalisation
Layer normalisation standardises the activations across the feature dimension at each position. For a vector x = [x1, x2, ..., xd], it computes the mean and variance across all d dimensions, then normalises:
Layer Normalisation
LayerNorm(x) = γ · (x − μ) / √(σ2 + ε) + β
μ and σ2 are the mean and variance of x. γ (scale) and β (shift) are learned parameters. ε is a small constant for numerical stability. This keeps activations in a well-behaved range throughout the deep network, preventing training instability.
The original Transformer stacks 6 encoder layers. Each layer refines the representations further. Early layers capture local syntactic patterns; deeper layers capture increasingly abstract, long-range semantic relationships. The residual connections ensure that gradients can flow through all 6 layers without vanishing.
The Decoder Stack
The decoder generates the output sequence one token at a time (during inference). Like the encoder, it consists of N = 6 identical layers, but each decoder layer has three sub-layers instead of two:
Sub-layer 1: Masked Multi-Head Self-Attention
The decoder self-attention is masked so that position i can only attend to positions ≤ i. This prevents the decoder from "cheating" by looking at future tokens during training. The mask sets attention scores for future positions to −∞ before the softmax, ensuring they receive zero weight.
Sub-layer 2: Cross-Attention (Encoder-Decoder Attention)
This is where the decoder "reads" the encoder's output. The Queries come from the decoder (what information does the decoder currently need?), while the Keys and Values come from the encoder's final output (what information is available in the input?). This allows each decoder position to attend to all positions in the input sequence.
Sub-layer 3: Position-wise Feed-Forward Network
Identical in structure to the encoder's feed-forward network. Each position is processed independently through a two-layer network with a ReLU activation.
As in the encoder, every sub-layer is wrapped with a residual connection and layer normalisation: output = LayerNorm(x + SubLayer(x)).
Cross-attention is like the construction team consulting the design documents. The encoder has produced a fully reviewed set of design documents (the encoder output). The decoder is the construction team, generating the build sequence one step at a time. At each construction step, the team consults the design documents (cross-attention) to determine what to build next. They can look at any part of the design — foundations, superstructure, finishes — but they can only see what they have already built (masked self-attention prevents looking at future steps).
The Final Output Layer
After the stack of N decoder layers, the output passes through a linear layer followed by a softmax to produce a probability distribution over the vocabulary. The token with the highest probability is selected as the output for that position. This process repeats autoregressively — each predicted token is fed back as input for the next position.
The original Transformer uses both encoder and decoder. However, many modern models use only one half: BERT uses only the encoder (for understanding tasks), while GPT uses only the decoder (for generation tasks). We will explore these variants in Sub-chapters 5.4 and 5.5.
The Full Architecture
Bringing all the components together, the Transformer architecture follows this data flow:
Encoder Side
- Input Embedding: convert tokens to dmodel-dimensional vectors
- Positional Encoding: add sinusoidal position signals
- ×N Encoder Layers: each containing:
- Multi-Head Self-Attention + Add & Norm
- Feed-Forward Network + Add & Norm
- Output: contextualised representations for all input positions
Decoder Side
- Output Embedding: convert previously generated tokens to vectors
- Positional Encoding: add sinusoidal position signals
- ×N Decoder Layers: each containing:
- Masked Multi-Head Self-Attention + Add & Norm
- Multi-Head Cross-Attention (Q from decoder, K/V from encoder) + Add & Norm
- Feed-Forward Network + Add & Norm
- Linear + Softmax: produce next-token probability distribution
Parameter Counts
The original Transformer base model had approximately 65 million parameters. Most parameters reside in the embedding layers and the feed-forward networks (which have the large inner dimension dff = 2048). The attention mechanisms themselves are relatively parameter- efficient — their power comes from the dynamic computation of attention weights, not from static parameters.
The paper presented two configurations: Base (dmodel=512, N=6, h=8, dff=2048, 65M params) and Big (dmodel=1024, N=6, h=16, dff=4096, 213M params). The Big model achieved the best translation results. Modern models have scaled to hundreds of billions of parameters using the same fundamental architecture.
Interactive Demo: Transformer Architecture Diagram
The interactive diagram below shows the full encoder-decoder Transformer architecture. Click on any block to see a detailed description of that component. Use the layer slider to expand or collapse the stack and observe how data flows through the architecture.
Click on any block in the diagram to learn about that component. Hover for highlights.
Notice the symmetry between the encoder and decoder stacks. Both use self-attention and feed-forward layers with residual connections. The decoder adds masked self-attention and cross-attention as additional sub-layers. Data flows bottom-to-top through both stacks, with the encoder's output feeding into every decoder layer's cross-attention.
Residual Connections & Layer Normalisation
These two techniques are not glamorous, but they are essential. Without them, stacking 6 (or 96) layers of attention and feed-forward networks would be practically impossible to train. Let us understand why.
The Vanishing Gradient Problem in Deep Networks
As a network grows deeper, gradients during backpropagation must travel through more and more layers. At each layer, the gradient is multiplied by the layer's Jacobian matrix. If these multiplications consistently shrink the gradient (eigenvalues < 1), the gradient effectively vanishes by the time it reaches the early layers — those layers stop learning.
How Residual Connections Help
With the residual formulation y = x + F(x), the gradient of the loss with respect to x includes a direct path:
dL/dx = dL/dy · (1 + dF/dx)
The "1" in the expression ensures that the gradient is at least as large as dL/dy, regardless of what dF/dx is. This creates a gradient highway through the network — gradients can flow from the loss all the way to the first layer without attenuation.
Why Layer Normalisation Instead of Batch Normalisation?
Batch normalisation, which normalises across the batch dimension, was the standard for CNNs. But for sequence models, batch normalisation has a critical flaw: sequences in a batch may have different lengths, making the batch statistics unreliable for positions near the end of shorter sequences. Layer normalisation sidesteps this entirely by normalising across the feature dimension within each individual example.
Pre-Norm vs. Post-Norm
The original Transformer applies layer norm after the residual addition (Post-Norm): LayerNorm(x + SubLayer(x)). Many modern implementations apply it before the sub-layer (Pre-Norm): x + SubLayer(LayerNorm(x)). Pre-Norm tends to be more stable for very deep models and often allows larger learning rates.
Interactive Demo: Positional Encoding Visualiser
The visualiser below plots the sinusoidal positional encoding values for different positions and dimensions. Each row is a position in the sequence; each column is a dimension of the encoding vector. Observe how low-frequency dimensions change slowly across positions (capturing coarse position information) while high-frequency dimensions oscillate rapidly (capturing fine position distinctions).
Hover to see exact PE values. Low dimensions = low frequency (slow variation). High dimensions = high frequency (rapid variation).
Key observations from the visualiser: the leftmost columns (lowest dimensions) create broad bands of colour that change gradually — these encode coarse position (beginning, middle, end of sequence). The rightmost columns oscillate rapidly, distinguishing between adjacent positions. Together they form a unique "fingerprint" for every position.
The sinusoidal encoding is reminiscent of binary number representations. In binary, the least significant bit alternates every number (0, 1, 0, 1, ...), the next bit every two numbers (0, 0, 1, 1, ...), and so on. Similarly, the lowest PE dimensions oscillate rapidly while higher dimensions oscillate more slowly. The encoding acts like a continuous, smooth version of binary counting.
Putting It All Together
Let us trace a complete forward pass through the Transformer to solidify the architecture. We will follow a translation task: English to French.
Step 1: Encode the Input
The English sentence "The bridge design is adequate" is tokenised into tokens: ["The", "bridge", "design", "is", "adequate"]. Each token is converted to a 512-dimensional embedding vector. Positional encodings are added, giving each token a unique position signature.
Step 2: Pass Through Encoder Stack
The 5 × 512 matrix passes through 6 encoder layers. In each layer, multi-head self-attention allows "bridge" to attend to "design" and "adequate" (learning that "adequate" modifies the "design" of the "bridge"). The feed-forward network then processes each enriched representation. After 6 layers, each token's vector captures rich contextual information about the entire sentence.
Step 3: Decoder Generates Output Autoregressively
The decoder begins with a start token. It uses masked self-attention (can only see previous outputs), cross-attention (reads the encoder output to find relevant source words), and the feed-forward network to predict the first French token: "Le". Then "Le" is fed back, and the decoder predicts "pont". This continues: "Le pont est adequat" until an end token is generated.
Step 4: Output Probability Distribution
At each decoder step, the final layer produces a vector that is projected to vocabulary size (e.g., 37,000 tokens) and passed through softmax. The model might output: P("Le") = 0.92, P("Un") = 0.04, P("La") = 0.03, etc. The highest-probability token is selected (or sampled from the distribution for more diverse outputs).
Training the Transformer
The original Transformer was trained on machine translation using a specific set of techniques that have since become standard practice for large models.
Learning Rate Schedule
The paper introduced a custom learning rate schedule with a warmup phase. The learning rate increases linearly for the first warmup_steps (4000 steps), then decreases proportionally to the inverse square root of the step number. This prevents early training instability while allowing aggressive learning in later stages.
lr = dmodel−0.5 · min(step−0.5, step · warmup−1.5)
Regularisation: Dropout and Label Smoothing
Dropout (rate 0.1) is applied after each sub-layer, to the attention weights, and to the positional encodings. This prevents overfitting by randomly zeroing activations during training. Label smoothing (ε = 0.1) replaces the hard 0/1 target distribution with a smoothed version, preventing the model from becoming overconfident in its predictions.
The original Transformer base model was trained on 8 NVIDIA P100 GPUs for 3.5 days (approximately 100,000 steps). The Big model took 3.5 days on 8 GPUs. This was dramatically faster than comparable RNN-based models because the Transformer's attention computation is fully parallelisable — no sequential dependency between time steps.
Key Takeaways
Summary
- The Transformer eliminates recurrence — it processes all positions in parallel using self-attention, dramatically increasing training speed on modern hardware.
- Multi-head attention runs h parallel attention heads, each learning to focus on different types of relationships (syntactic, semantic, positional, etc.).
- Positional encoding injects position information via sinusoidal functions, since self-attention is inherently position-agnostic.
- Encoder = N layers of [Self-Attention + FFN], each with residual connections and layer normalisation.
- Decoder = N layers of [Masked Self-Attention + Cross-Attention + FFN], each with residual connections and layer normalisation.
- Cross-attention connects the decoder to the encoder, allowing the output generator to consult the input representations at every layer.
- Residual connections create gradient highways; layer normalisation keeps activations stable.
In Sub-chapter 5.4, we will explore BERT (Bidirectional Encoder Representations from Transformers) — an encoder-only Transformer that learns rich language representations through masked language modelling and next-sentence prediction. BERT revolutionised transfer learning in NLP and has direct applications in document analysis and specification parsing for civil engineering.
CE Applications: Transformer Architecture in Practice
Transformers process entire sequences in parallel — making them ideal for analyzing large engineering documents, multi-sensor data streams, and complex design specifications.
Specification Document Analysis
A transformer can process an entire 200-page project specification simultaneously, finding cross-references between structural, geotechnical, and hydrological requirements that RNNs would miss.
Multi-Sensor Fusion
Parallel self-attention allows transformers to fuse data from accelerometers, strain gauges, temperature sensors, and GPS simultaneously — capturing correlations between sensor types for SHM.
Speed Advantage for Design Iteration
Parallel processing lets engineers run hundreds of design variations through AI evaluation in minutes. A soil-structure interaction model that took hours with sequential methods finishes in seconds.
Knowledge Check
Test your understanding of the Transformer architecture with these four questions. Select the best answer for each.
Why does the Transformer need positional encoding?
In the decoder, what is the purpose of masking in the self-attention layer?
In the cross-attention layer of the decoder, where do the Queries, Keys, and Values come from?
What is the primary purpose of residual connections in the Transformer architecture?