Transformers
How transformer networks use self-attention to relate every element of a sequence to every other, the architecture behind modern language models, vision models and protein-structure predictors.
What it is
The transformer is a neural network architecture introduced in the 2017 paper “Attention Is All You Need” (Vaswani et al.). Instead of processing a sequence step by step like a recurrent network (see RNN and LSTM), it uses self-attention to let every element of the input look at every other element directly and decide which ones are relevant. This allows all positions to be processed in parallel on GPUs and makes long-range relationships easy to learn. Transformers underlie large language models (GPT, Claude, Llama, BERT), vision transformers (ViT), speech models, protein structure prediction (AlphaFold), weather forecasting models and multimodal systems. They are trained on very large data sets, and then adapted to specific tasks.
It answers questions such as: How can a model capture dependencies between distant words, pixels or residues? How can one pretrained model be reused for many tasks? How are sequences generated token by token? Why do scaling model size, data and compute improve performance so predictably? Transformers are powerful but demand substantial compute and data.
Fundamentals
Tokens, embeddings and positional information
Input is split into tokens (words, sub-words, image patches, amino acids, time steps). Each token is mapped to a learned vector of dimension d, the embedding. Since attention itself ignores order, positional encodings are added: the original used fixed sinusoids, and modern models use learned embeddings or rotary position embeddings (RoPE) or relative biases. The sequence of vectors then passes through a stack of identical layers (6 in the original base model, 12 to over 100 in large models).
Scaled dot-product self-attention
Each token’s vector is projected into a query (Q), key (K) and value (V) using learned matrices. Attention computes Attention(Q, K, V) = softmax(QKT/√dk)V. The product QKT gives a score for every pair of tokens (how much token i should attend to token j), the division by √dk keeps scores from growing too large for the softmax, softmax turns scores into weights that sum to 1, and the output is a weighted average of the values. Multi-head attention runs h such attentions in parallel with different projections (for example 8 to 96 heads), letting the model attend to different relations (syntax, position, meaning) at once, then concatenates the results. The cost is O(n2d) for sequence length n, which is why very long contexts are expensive, and efficient variants (sparse, linear, FlashAttention, sliding windows) reduce memory or time.
The transformer block
Each layer combines attention with a position-wise feed-forward network (two linear layers with a nonlinearity such as GELU, with hidden size about 4d), each wrapped in a residual connection and layer normalization: x ← LayerNorm(x + Sublayer(x)), or the “pre-norm” variant. The residual path eases training of very deep stacks. Approximate parameter count per layer is 12d2 (4d2 for attention and 8d2 for the feed-forward part), so GPT-2 small (d = 768, 12 layers) has about 85 million parameters in its layers plus about 38 million in token embeddings, close to its 124 million total. Three families exist. Encoder-only models (BERT) see the full sequence in both directions and suit classification, tagging and embeddings. Decoder-only models (GPT) use causal (masked) attention, so each token sees only earlier tokens, and generate text one token at a time. Encoder–decoder models (the original transformer, T5) suit translation and summarization, with cross-attention from decoder to encoder.
Training: pretraining, fine-tuning and scaling
Language models are pretrained by self-supervision: predict the next token (autoregressive) or masked tokens, minimizing cross-entropy loss over trillions of tokens, using optimizers such as AdamW with warm-up and decay schedules, mixed precision and parallelism across many GPUs. The pretrained model is then fine-tuned on a smaller labeled set or adapted by instruction tuning and reinforcement learning from human feedback. Parameter-efficient methods such as LoRA train small low-rank updates while freezing the rest. Empirical scaling laws show that loss falls smoothly as a power law with parameters, data and compute, guiding compute-optimal training. For generation, decoding uses greedy search, beam search or sampling with temperature and top-p, and a KV cache stores keys and values to avoid recomputation. Vision transformers cut images into 16 × 16 patches treated as tokens; Swin and others add locality.
Uses in science, typical applications and limits
Beyond language, transformers predict protein structure and function (AlphaFold uses attention-based modules), analyze genomes, forecast weather, model molecules and materials, process time series and handle multimodal data. Applications also include code generation, search and question answering (see natural language processing and large language models). Limits: quadratic attention cost, large data and energy needs, hallucination in generative models, sensitivity to training data bias, difficulty in interpretation (attention weights are not complete explanations), and the need for careful evaluation of reliability. Common libraries: PyTorch, Hugging Face Transformers, JAX.
Basic operation
- Define the task and data. Decide on classification, generation or embedding, and gather suitable text or other sequences.
- Tokenize. Convert input into tokens with a tokenizer matching the model.
- Choose a pretrained model. Select an encoder, decoder or encoder–decoder model of suitable size.
- Adapt it. Fine-tune fully, use LoRA, or provide examples in the prompt.
- Train or evaluate. Monitor loss on validation data and avoid overfitting.
- Test on held-out data. Use task-appropriate metrics and check failure cases.
- Deploy carefully. Use batching, caching and monitoring.
- Collect the output. You obtain predictions or generated text; attention mechanics and fine-tuning are covered in the video.
Good practice
- Start from a pretrained model. Training from scratch needs vast resources.
- Check for data leakage. Benchmarks may overlap with pretraining data.
- Evaluate beyond averages. Test on rare cases and subgroups.
- Do not treat attention as explanation. Use dedicated interpretation methods.
- Track compute and carbon. Report resources used.
- Verify generated content. Models can state falsehoods confidently, so check facts and review outputs before use in medical, legal or scientific settings, and respect copyright and privacy in training data.
Key terms
- Self-attention — a mechanism where each token weights all tokens in the sequence by relevance.
- Query, key, value — the three projections used to compute attention weights and outputs.
- Multi-head attention — several attention operations run in parallel.
- Positional encoding — information that tells the model the order of tokens.
- Causal mask — a rule preventing tokens from attending to later positions.
- Pretraining / fine-tuning — learning general patterns first, then adapting to a task.
- Token — the basic unit of input, such as a word piece or image patch.
Video coming soon
About five minutes on Transformers: how it works in detail, how the data is acquired, and how it is analyzed.
More in 4.3 AI and Machine Learning
- Regularized linear models
- Decision trees and random forests
- Gradient boosting (XGBoost)
- Support vector machines
- k-NN
- k-means
- Gaussian processes
- Neural networks
- CNNs
- RNN/LSTM
- Transformers
- Autoencoders
- GANs
- Diffusion models
- Graph neural networks
- Reinforcement learning
- Transfer learning
- Federated learning
- Explainable AI (SHAP, LIME)
- Physics-informed neural networks
- Bayesian optimization
- Active learning
- Symbolic regression
- Genetic algorithms and particle swarm optimization
- Dimensionality reduction (t-SNE, UMAP)
- NLP and large language models
- Retrieval-augmented generation
- Computer vision (detection, segmentation)
- Anomaly detection
- Machine-learned interatomic potentials
- AutoML
