Robots Atlas>ROBOTS ATLAS
Architecture

Transformer

2017ActiveUpdated: 24 August 2026Published
Key innovation
Self-attention mechanism replacing recurrence and convolutions, enabling parallel sequence processing and modeling of long-range dependencies.
Category
Architecture
Abstraction level
Building block
Operation level
Architecture blockModel
Use cases
Machine translation (WMT EN-DE, EN-FR)Large language models (GPT, LLaMA, Claude, Gemini)Encoder-only language understanding models (BERT, RoBERTa)Code generation and completionVision Transformer — image classification and detectionMultimodal models (CLIP, Flamingo, GPT-4o)Automatic speech recognition (Whisper)Protein and computational biology models (AlphaFold, ESM)Tabular foundation models (TabPFN)Constituency parsing and sequence-to-sequence tasks

How it works

The input is tokenized and embedded in d_model space, then positional encoding is added. The sequence passes through a stack of identical blocks: each block contains multi-head self-attention (Query/Key/Value computed from embeddings; attention(Q,K,V)=softmax(QK^T/√d_k)V) and a position-wise feed-forward network (typically 4× the width of d_model). Residual connections and LayerNorm are applied around each sublayer. In the encoder-decoder variant, the decoder has an additional cross-attention layer over the encoder output and causal masking in self-attention.

Problem solved

Modeling long-range dependencies in sequences with fully parallelizable training computations — something RNNs/LSTMs could not provide due to the sequential nature of their temporal propagation.

Components

Multi-Head Self-AttentionModeling contextual dependencies between sequence positions

Mechanism allowing every position in the sequence to attend to all other positions. The input is projected into three matrices: Query (Q), Key (K), Value (V). Attention weights are computed as softmax(QK^T/sqrt(d_k)) multiplied by V. Multiple 'heads' perform this operation in parallel in low-dimensional subspaces, and the results are concatenated and projected through W_O.

INB = batch, T = sequence length, d_model = representation dimension (e.g., 512, 4096).
OUTSequence of contextual representations with the same shape as the input.
Scaled Dot-Product AttentionClassical implementation from Vaswani 2017.
FlashAttentionI/O-aware implementation reducing HBM↔SRAM data movement (Dao et al. 2022, FlashAttention-2 2023, FlashAttention-3 2024).
Grouped-Query Attention (GQA)Sharing K/V across groups of Q heads — a compromise between MHA and MQA, used in LLaMA 2/3.
Multi-Query Attention (MQA)One K/V set shared across all Q heads — drastic KV-cache reduction (Shazeer 2019).
Sliding Window / Local AttentionRestriction of attention to a local window (Longformer, Mistral) — linear complexity.

Official

Position-wise Feed-Forward NetworkNon-linear per-position transformation of representations; the main carrier of parametric capacity

Two-layer MLP (Linear → activation → Linear) applied independently to each position in the sequence. Originally: ReLU, hidden dimension d_ff = 4·d_model. In modern models often GLU/SwiGLU/GeGLU (LLaMA, PaLM).

Vanilla FFN (ReLU)
SwiGLUGated Linear Unit with Swish activation — default in LLaMA, PaLM, Mistral (Shazeer 2020).
Mixture of Experts (MoE) FFNReplacing FFN with a set of conditionally activated experts (Switch Transformer, GShard, Mixtral, DeepSeek-MoE).

Official

Layer NormalizationStabilization of gradients and activations in deep layer stacks

Per-token normalization of activations within a layer, crucial for training stability in deep Transformers. Originally Post-LN (after sub-block); modern models predominantly use Pre-LN (before sub-block) or RMSNorm (a simplified version without centering).

Post-LN
Pre-LN
RMSNorm

Official

Residual ConnectionsGradient and information propagation through deep stacks

Adding the sub-block input to its output (y = x + f(x)). Enables training of hundreds-of-layers models without vanishing gradients and provides a 'residual stream' — an interpretable inter-layer communication channel (Elhage et al. 2021).

Positional EncodingIntroducing sequence order into the permutation-invariant attention mechanism

Mechanism for injecting token position information into a model that lacks recurrence. Originally: additive sinusoidal PE. Today, relative positions dominate (RoPE — Rotary Position Embedding, ALiBi), which generalize to longer contexts.

Sinusoidal (absolute)
Learned absolute
RoPE (Rotary)
ALiBi

Official

Implementation

Implementation pitfalls
Post-LN instability in deep modelsHigh

The original Post-LayerNorm layout (LN after the residual) leads to large activation norms in deep stacks (>12 layers) and requires expensive learning-rate warmup and careful initialization tuning. Without it, training diverges.

Fix:Use Pre-LN or RMSNorm. Most modern Transformers (GPT-2+, LLaMA, PaLM) use Pre-LN.
Missing QK^T scaling by sqrt(d_k)Critical

If the Q·K dot product is not divided by sqrt(d_k), softmax saturates for large d_k, gradient vanishes, and the model fails to learn.

Fix:Always divide attention logits by sqrt(d_k) before softmax — this is not an optional optimization, it is a numerical foundation.
Materializing full T×T attention matrixHigh

A naive implementation allocates a T×T matrix in HBM, which for T=32K and fp16 requires 2 GB per layer — quickly exhausting GPU memory at long contexts.

Fix:Use FlashAttention (PyTorch SDPA backend, xFormers, Triton kernels) — tile-based, never materializes the full matrix.
KV-cache grows linearly with context lengthHigh

During autoregressive inference, the KV-cache occupies O(L · T · d_model · 2) memory. For LLaMA-3-70B at T=128K this is ~40 GB — limiting batch size and throughput.

Fix:GQA/MQA (K/V head reduction), paged attention (vLLM), KV-cache quantization (Q4/Q8), sliding window attention.
Incorrect causal mask in the decoderCritical

A bug in the triangular mask (e.g., off-by-one, masking after softmax instead of before) causes future-token leakage during training — the model looks great in training but fails at inference.

Fix:Use built-in implementations (PyTorch nn.Transformer, HF transformers). Write tests verifying that prediction at t does not depend on tokens >t.
Confusing Pre-LN and Post-LN when loading weightsMedium

BERT (Post-LN) and GPT-2/LLaMA (Pre-LN) weights are not interchangeable in the same code — loading weights into the wrong layout produces garbage predictions without a runtime error.

Fix:Always check the model's config.json and use the appropriate class from the transformers library.

Evolution

Original paper · 2017 · NeurIPS 2017 · Ashish Vaswani
Attention Is All You Need
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin
2014
Attention mechanism in seq2seq

Bahdanau et al. introduce soft attention in RNN-based neural machine translation — a precursor to self-attention.

2017
Attention Is All You Need
Inflection point

Vaswani et al. publish the Transformer architecture, eliminating recurrence in favor of pure multi-head self-attention.

2018
BERT and GPT-1
Inflection point

Devlin et al. (BERT, encoder-only) and Radford et al. (GPT, decoder-only) prove that Transformer pre-training on massive corpora + fine-tuning is the dominant NLP paradigm.

2020
GPT-3 and scaling laws
Inflection point

Brown et al. (GPT-3, 175B) and Kaplan et al. (scaling laws) demonstrate predictable performance scaling with parameters, data, and compute.

2020
Vision Transformer (ViT)
Inflection point

Dosovitskiy et al. show that a Transformer operating on image patches outperforms CNNs on ImageNet — the start of Transformer expansion beyond NLP.

2022
FlashAttention

Dao et al. introduce I/O-aware exact attention, reducing HBM↔SRAM data movement and making long-context training practical.

2023
Mixture-of-Experts mainstream (Mixtral 8x7B)

Mistral AI releases Mixtral — an open-weight MoE Transformer matching GPT-3.5 at a fraction of inference cost.

2024
Reasoning models (o1, DeepSeek-R1)
Inflection point

OpenAI o1 and DeepSeek-R1 introduce test-time compute scaling via long chain-of-thought built on Transformer — a new axis of scaling.

Hyperparameters (configurable axes)

Number of layers (depth)Critical

Number of identical blocks in the encoder/decoder stack. Increases capacity and abstraction ability, but linearly raises cost and training-instability risk.

6Base and Big in Vaswani et al. 2017 (N=6).
12GPT-1, BERT-base.
96GPT-3 175B.
Model dimension (width)Critical

Dimension of the token representation and residual stream. The primary determinant of parametric capacity; scales projection and FFN cost quadratically.

512Base model (Vaswani et al. 2017).
1024Big model (Vaswani et al. 2017).
12288GPT-3 175B.
Number of attention headsHigh

Number of parallel heads in multi-head attention. Each head operates in a subspace of dimension d_k = d_model/h, learning distinct relational patterns.

8Base model (d_k=d_v=64).
16Big model (d_k=d_v=64).
FFN hidden dimensionHigh

Inner dimension of the feed-forward network, typically 4·d_model. The main carrier of parameters and FLOPs outside attention.

2048Base model (4·512).
4096Big model (4·1024).
Context lengthHigh

Maximum sequence length processed at once. Bounded by quadratic attention complexity; a target of heavy optimization (FlashAttention, RoPE, sliding window).

512BERT.
2048GPT-3.
128K+Modern long-context LLMs.
Dropout rateMedium

Dropout probability applied to sub-layer outputs and embedding+PE sums. Regularization against overfitting.

0.1Base model (Vaswani et al. 2017).
0.3Big model (except EN-FR, where 0.1).

Computational complexity

Time complexity: O(T² · d_model) per warstwa (uwaga) + O(T · d_model · d_ff) (FFN). Space complexity: O(T² + T·d_model) per warstwa (naiwnie) → O(T·d_model) z FlashAttention.

Compute bottleneck

Quadratic attention complexity

Standard self-attention scales as O(T²) with respect to sequence length, becoming the dominant cost for long contexts (>8K tokens). Memory-wise, the T×T attention matrix becomes infeasible to materialize without tile-based techniques (FlashAttention).

Depends on
Sequence length (T)Head dimension (d_k)HBM bandwidth

Execution paradigm

Primary mode
Dense

The MoE variant (Switch Transformer, Mixtral) shifts the paradigm to conditional/mixture, but this is an extension of the classical Transformer, not the Transformer itself.

Activation pattern
All paths active
Additional modes
Sparse
Routing mechanism

Classical Transformer activates all parameters for every token. Routing appears only in MoE-FFN variants, where a subset of parameters (experts) is conditionally activated.

Parallelism

Parallelism level
Fully parallel

Full parallelism over sequence positions was the main reason Transformers replaced RNNs — RNNs required sequential unrolling in time even during training.

Scope
TrainingAcross tokensAcross layersAcross devices
Constraints
!Decoder token generation at inference time is sequential (each token depends on previous ones). However, prefill (prompt encoding) is fully parallel.
!Decoder training uses a causal mask, but all positions are computed in parallel (teacher forcing).

Hardware requirements

Primary

Dense matmul (QK^T, attention·V, FFN) maps perfectly to Tensor Cores. NVIDIA H100/H200/B200 with FP8/FP16/BF16 are the de facto standard for Transformer training and inference.

Primary

Google TPU v4/v5/v6 were designed with Transformers in mind (PaLM, Gemini). XLA + JAX/Flax deliver high performance at large scale.

Limited

Inference of small Transformers (e.g., BERT-base) on CPU AVX-512/AMX is feasible (Intel oneDNN, llama.cpp), but latency scales linearly with sequence length.

Possible

FPGAs are used in specialized low-latency applications (HFT, edge), but HBM memory limits and toolchain constraints make them a niche choice.