Self-Attention and Transformers
Self-Attention and Transformers
Self-attention and Transformer architectures are foundational techniques in modern natural language processing and have also become important across many other areas of artificial intelligence. They address major limitations of recurrent neural networks while enabling highly parallel computation over long sequences.
Recurrent Neural Networks as the Earlier Standard
Before Transformers, a strong default architecture for many NLP tasks used recurrent neural networks, especially LSTMs.
A typical sequence-to-sequence system contained:
A bidirectional LSTM encoder that read the input sequence from both directions and produced contextual representations.
A unidirectional LSTM decoder that generated the output sequence one token at a time.
An attention mechanism that allowed the decoder to access different parts of the encoder’s representation instead of forcing the entire source sentence into one vector.
This architecture was effective for tasks such as:
Machine translation
Text generation
Syntactic parsing
Sequence labeling
Other sequence-to-sequence prediction problems
Attention was originally introduced largely to solve an information bottleneck: the entire source sentence should not have to be compressed into a single fixed-size vector before decoding begins.
However, recurrent models have two important structural limitations:
Long-distance interactions take many sequential steps.
The computation cannot be fully parallelized across positions.
Transformers replace recurrence with attention-based operations that can process the sequence more directly and in parallel.
Limitations of Recurrent Neural Networks
Linear Interaction Distance
A recurrent network processes a sequence in order. For a left-to-right RNN, the representation at position i depends on the representation at position i−1, which depends on position i−2, and so on.
For example, in the sentence:
The chef who went to the store and picked up the ingredients and loves garlic was tired.
The words chef and was are syntactically related, but many words occur between them. In an RNN, information must travel through a long chain of recurrent updates:
The number of computational steps between two words grows linearly with their distance in the sequence.
This creates a linear interaction distance problem:
Nearby words can interact after only a few recurrent steps.
Distant words must communicate through many intermediate hidden states.
Learning long-distance dependencies becomes more difficult.
Gradients must propagate through many transformations.
Even LSTMs, which handle gradients better than simple RNNs, do not eliminate the problem entirely.
The sequence’s linear order is useful for some linguistic relationships, but it is not always the best computational structure. Words that are far apart in the sequence may be closely related syntactically or semantically.
Key idea: A model should allow potentially related words to interact directly, rather than forcing information to travel step by step through every intervening word.
Sequential and Non-Parallelizable Computation
RNNs also depend on the sequence index, sometimes described as their dependence on time.
The hidden state at position t cannot be computed until the hidden state at position t−1 is available:
Consequently:
Position 5 cannot be computed before position 4.
Position 4 cannot be computed before position 3.
The number of sequential operations grows with the sequence length.
GPUs cannot fully exploit parallel computation across positions.
Although each individual recurrent operation may use efficient matrix multiplication, the operations themselves must occur in sequence. A larger GPU does not remove this dependency.
This is a major disadvantage because GPUs are especially effective when many independent operations can be carried out simultaneously.
Attention as a Direct Access Mechanism
Attention allows a representation at one position to access information stored at many other positions directly.
In a decoder, attention can allow the current output token to look back at relevant encoder states. In self-attention, each word can attend to other words in the same sequence.
The central intuition is:
Each word provides a query describing the information it seeks.
Other words provide keys that indicate what information they contain.
Other words also provide values, which are the information actually retrieved.
Similarity between a query and each key determines how strongly the corresponding value contributes to the output.
This makes attention similar to a fuzzy lookup in a key-value store.
Exact Lookup Versus Soft Lookup
An ordinary dictionary or lookup table works through an exact match:
A query is provided.
The query matches one key.
The corresponding value is returned.
Attention performs a soft version of this process:
A query is compared with every key.
Each comparison produces a similarity score.
A softmax converts the scores into weights.
The output is a weighted average of the values.
Instead of choosing one value, attention can combine information from many values.
If the attention weights are αij, then the output for position i is:
where:
n is the sequence length.
vj is the value associated with position j.
αij indicates how strongly position i attends to position j.
Because every position can potentially interact with every other position in one operation, attention removes the linear interaction-distance problem.
Self-Attention
Input Word Representations
Consider a sequence of n words:
Let the word embedding matrix be:
where:
D is the embedding or model dimensionality.
∣V∣ is the vocabulary size.
Each word wi is represented by a one-hot vector or an equivalent vocabulary-index representation. Applying the embedding matrix produces a vector:
Each xi is a non-contextual word embedding. It represents the identity of the word but does not yet incorporate the surrounding sentence.
Queries, Keys, and Values
Self-attention transforms every input embedding into three vectors:
A query vector
A key vector
A value vector
Using learnable matrices Q, K, and V:
Typically, the matrices have shapes such as:
The three transformations give every word three different roles:
The query represents what the word is looking for.
The key represents what the word can be matched on.
The value represents the information the word contributes when selected.
The query, key, and value for the same word do not need to be identical. The separate matrices allow the model to learn distinct functions for searching, matching, and providing information.
Similarity Scores
For a target position i and a source position j, self-attention computes a similarity score by taking the dot product between the query at position i and the key at position j:
Interpretation:
A large positive score means that position j appears highly relevant to position i.
A low or negative score means that position j appears less relevant.
The score is a real-valued, unnormalized compatibility measure.
The model computes these scores for all pairs of positions.
Attention Weights
The raw scores are converted into normalized attention weights using a softmax over all possible source positions:
For each target position i, the weights satisfy:
The weights can be interpreted as a soft distribution over the positions that position i should consult.
Contextual Output Representations
The output for position i is the weighted sum of all value vectors:
This output is now a contextual representation because it incorporates information from other words in the sequence.
For example, when representing the word learned in:
I went to Stanford’s CS224N and learned.
the model may attend to:
Stanford because the institution provides contextual information.
CS224N because the course identifies what was learned.
I went because these words contribute syntactic context.
learned itself, depending on what the learned representation requires.
The attention pattern is not manually specified. The query, key, and value matrices are learned from data.
Why Separate Query and Key Matrices?
The score can be written as:
Thus, the pair of matrices Q and K collectively defines a learned similarity function.
Using separate matrices is useful because:
The query and key roles are conceptually different.
The model can transform the same word differently depending on whether it is searching or being searched.
The resulting interaction matrix can be represented efficiently through lower-dimensional projections.
The model can learn whether a word should attend to itself or to other words.
For example, self-attention does not automatically require a word to attend strongly to itself. The learned transformations may make qi⊤ki large, small, or negative.
Matrix Form of Self-Attention
Computing attention one word at a time would be inefficient. Instead, all word representations are stacked into a matrix:
The query, key, and value matrices for the entire sequence are computed as:
Each has shape n×D.
The matrix of all pairwise query-key scores is:
Since:
XQ has shape n×D.
XK⊤ has shape D×n.
the result S has shape:
The entry Sij is the score eij.
After applying softmax independently across each row:
the complete self-attention output is:
where:
A contains all attention weights.
XV contains all value vectors.
O contains the contextual output for every sequence position.
This matrix formulation allows the entire sequence to be processed efficiently on a GPU without an explicit loop over positions.
Positional Information
Why Self-Attention Needs Position Information
Self-attention by itself does not know the order of the input elements.
Suppose the model receives:
Zuko made his uncle.
and:
His uncle made Zuko.
If the model only receives the same word embeddings and applies the same permutation-independent self-attention operation, it can produce the same representations after the words are reordered. However, the two sentences have different meanings because word order determines grammatical roles.
Self-attention naturally operates on a set of vectors unless positional information is added.
Key idea: Word identity alone is not enough. A sequence model must also represent where each word occurs or how it relates positionally to other words.
Adding Position Embeddings
A position i can be represented by a vector pi∈RD.
The word embedding and position embedding are combined by addition:
The resulting vector contains information about both:
Which word occurs at the position.
Where that word occurs in the sequence.
Position information is often added at the input to the network rather than repeatedly at every layer. Once position information has entered the computation, later layers can use it when producing contextual representations.
Sinusoidal Position Representations
One early approach uses deterministic sine and cosine functions with different frequencies across dimensions. A typical form is:
where:
i is the sequence position.
k indexes the dimensions.
D is the model dimensionality.
Different dimensions use different periods:
Some dimensions change rapidly across positions.
Others change more slowly.
Together, the dimensions provide a distinctive representation of position.
The motivation is that periodic functions might allow the model to infer relative or absolute position and potentially generalize to sequence lengths longer than those seen during training.
In practice, sinusoidal representations are not always the most effective choice, and the hoped-for extrapolation to longer sequences is not guaranteed.
Learned Position Embeddings
A more direct approach is to learn a position embedding matrix:
where N is the maximum supported sequence length.
The position vector at index i is learned as a parameter, and the model uses:
Advantages:
The model can learn whatever positional representation is most useful for the task.
The representation is optimized jointly with the rest of the network.
It is simple to implement.
Limitation:
The model cannot directly represent positions beyond the maximum learned length N.
A sequence longer than N may cause an error or require a special extension method.
Long sequence lengths remain difficult because self-attention has quadratic computational and memory costs.
Relative Position Representations
Absolute position embeddings identify a word by its index, such as position 5. However, many linguistic relationships depend more naturally on relative distance:
A word immediately before another word.
A word three positions after another word.
A word’s relation in a dependency tree.
For this reason, alternative methods represent relative positions or structural relationships rather than only absolute indices. These methods can potentially generalize better and encode more linguistically meaningful relationships.
Adding Nonlinear Computation
The Problem with Repeated Self-Attention Alone
Self-attention computes weighted averages of value vectors. If multiple self-attention layers are stacked without nonlinear transformations, the result can behave like repeated averaging.
Repeated averaging alone does not provide the full expressive power associated with deep neural networks.
A solution is to apply a feed-forward network independently to each position after self-attention.
Position-Wise Feed-Forward Network
For each contextual output vector oi, a multilayer perceptron computes:
where:
W1 and W2 are learned matrices.
b1 and b2 are bias vectors.
σ is a nonlinear activation function.
The same feed-forward network is applied independently to every sequence position:
The feed-forward layer therefore:
Adds nonlinear modeling capacity.
Processes the result of contextual attention.
Allows each position to transform its representation independently.
Can contain substantial computation that remains highly parallelizable.
A typical Transformer block alternates between:
Self-attention, which mixes information across positions.
A position-wise feed-forward network, which transforms each position separately.
Causal Masking
Why Future Information Must Be Hidden
In autoregressive language modeling or sequence decoding, the representation used to predict the next token must not access future tokens.
For example, when predicting:
who
from:
The chef
the model may use the start symbol, The, and chef, but it must not already see who or any later word.
If the model could inspect the answer during training, the task would become artificially easy and the model would not learn the intended conditional prediction problem.
Applying a Causal Mask
The unmasked score is:
For causal self-attention, the model keeps scores for positions at or before the current position:
The softmax then maps the masked future scores to zero:
Therefore, position i can attend only to positions 1 through i.
The resulting attention matrix has a lower-triangular structure:
Position 1 attends only to position 1.
Position 2 attends to positions 1 and 2.
Position 3 attends to positions 1, 2, and 3.
Later positions are masked out.
Masking and Parallelization
Causal masking prevents information leakage while preserving efficient matrix computation.
Rather than separately computing each position’s attention over only its past, the model:
Computes the complete n×n score matrix.
Replaces illegal future scores with negative infinity.
Applies softmax.
Thus, the entire sequence can still be processed in parallel during training, even though the attention pattern is causal.
During generation, output tokens are still produced one at a time because each new token depends on the tokens generated previously.
Encoder and Decoder Masking
Encoder Self-Attention
An encoder generally uses unmasked self-attention because it is allowed to access the entire input sequence.
For machine translation, the encoder should be able to represent each source word using:
Words before it.
The word itself.
Words after it.
This produces bidirectional contextual representations.
Decoder Self-Attention
A decoder generally uses causal masked self-attention because it generates the output from left to right.
The decoder cannot use future target words when predicting the next token.
Padding Masks
Sequences in a batch often have different lengths. They are padded to a common length. Padding positions should not influence actual representations.
The model can mask padded positions by assigning them scores near negative infinity, causing their attention weights to become zero.
Multi-Head Self-Attention
Motivation
A single attention operation may need to capture several different kinds of relationships simultaneously.
For example, when representing a word, the model might need to attend to:
Syntactically related words.
Semantic or topical information.
Named entities.
Long-distance dependencies.
The word itself.
Words with particular grammatical roles.
A single set of query, key, and value transformations may have difficulty representing all these relationships at once.
Multi-head attention addresses this by running several self-attention mechanisms in parallel.
Independent Attention Heads
Suppose there are H attention heads. Each head has its own query, key, and value matrices:
for head h.
Instead of projecting each vector into a full D-dimensional space, each head usually projects into a smaller space of dimensionality:
For each head:
Each head computes attention independently:
Each Oh has shape n×dh.
Combining the Heads
The outputs from all heads are concatenated:
The concatenated result has dimensionality D per position. A final learned linear transformation combines the information:
where WO is an output projection matrix.
The complete process is:
Project the input into separate query, key, and value spaces for each head.
Compute attention independently in each head.
Allow each head to focus on different positions or relationship types.
Concatenate the head outputs.
Apply a final linear transformation.
Tensor Implementation
Multi-head attention can be implemented efficiently through reshaping rather than explicit loops.
For example, a query matrix of shape n×D can be reshaped into:
The head dimension can then be moved to the front, allowing the attention computation to treat heads similarly to a batch dimension.
This does not necessarily require more computation than a single full-dimensional attention operation because each head works in a lower-dimensional space.
The model typically chooses the number of heads so that each head still has a reasonable number of dimensions. Increasing the total model dimensionality often allows the use of more heads.
Specialization of Attention Heads
The model is not explicitly forced to make different heads learn different functions. However, because each head has independent parameters and receives different optimization signals, heads often specialize.
Possible roles include:
Tracking syntactic dependencies.
Connecting a pronoun to its antecedent.
Aggregating broad contextual information.
Attending to nearby words.
Attending to particular semantic categories.
Some redundancy can occur, and certain heads may contribute less than others. Nevertheless, multi-head attention is empirically much more effective than using only a single attention head.
Scaled Dot-Product Attention
Problem with Large Dot Products
As the dimensionality of query and key vectors increases, their dot products can become large in magnitude, even when the vectors are random or not strongly related.
Large softmax inputs create a sharply peaked distribution:
One or a few positions receive almost all the probability.
Most other positions receive probabilities near zero.
The softmax gradients become very small.
Learning becomes more difficult, especially at initialization.
Scaling the Scores
The standard solution is to divide the query-key dot products by the square root of the head dimensionality:
where dh is the dimensionality of each attention head.
The scaling factor:
Keeps the scores at a more manageable numerical range.
Prevents the softmax from becoming excessively sharp.
Produces healthier gradients.
Improves optimization stability.
Scaled dot-product attention is generally assumed in Transformer implementations.
Residual Connections
Basic Structure
A residual connection adds a layer’s input to its output.
If a layer computes F(x), the residual version computes:
In a Transformer, F may be:
A self-attention sublayer.
A feed-forward sublayer.
A cross-attention sublayer.
Benefits
Residual connections make deep networks easier to train.
Improved Gradient Flow
The residual path provides a direct route for gradients:
Even if the gradient through F becomes small, the identity component provides a direct gradient path.
This helps reduce the effects of:
Vanishing gradients.
Difficult optimization landscapes.
Degradation as more layers are added.
Learning Residual Corrections
Instead of requiring each layer to learn a complete new representation, the layer can learn only the change or residual needed relative to its input.
Near-Identity Initialization
If F(x) is initially small, then:
Thus, the network initially behaves somewhat like an identity mapping, which can provide a stable starting point for optimization.
Layer Normalization
Purpose
Layer normalization stabilizes the representations passed between sublayers.
Neural network activations can vary substantially:
Some dimensions may become very large.
Others may become very small.
Different layers may produce outputs with different scales.
Uncontrolled variation can make optimization more difficult.
Layer normalization normalizes the features of an individual representation vector.
Computing the Mean and Standard Deviation
Let x∈RD be the representation of one position.
The mean across its dimensions is:
The variance is estimated as:
The normalized representation is:
where ϵ is a small positive constant that prevents division by zero.
Some implementations then apply learned scale and offset parameters:
where:
γj is a learned multiplicative scale.
βj is a learned additive offset.
The result has approximately controlled mean and standard deviation for each individual position.
Layer Normalization Versus Batch Normalization
Layer normalization computes statistics independently for each individual representation.
It does not:
Combine statistics across different positions in the sequence.
Combine statistics across different examples in a batch.
This differs from batch normalization, whose statistics depend on other examples in the batch. Layer normalization is particularly suitable for sequence models because each example can be normalized independently, avoiding unwanted dependence on unrelated examples.
Transformer Blocks
A standard Transformer block combines attention, residual connections, normalization, and a feed-forward network.
A decoder block commonly follows this pattern:
Masked multi-head self-attention.
Residual connection and layer normalization.
Position-wise feed-forward network.
Residual connection and layer normalization.
In simplified notation:
Several blocks are stacked:
The parameters are generally independent across blocks. Each block can therefore learn a different level or type of representation.
A final prediction layer can use the resulting representations for tasks such as:
Predicting the next token.
Classifying a sentence.
Producing a translation.
Predicting labels for each token.
Transformer Decoder
A Transformer decoder is designed for autoregressive generation.
Its main components are:
Positional representations.
Masked multi-head self-attention.
Residual connections.
Layer normalization.
Position-wise feed-forward networks.
Repeated Transformer blocks.
An output prediction layer.
The causal mask ensures that the representation at position i depends only on positions up to i.
This makes it possible to model a sequence probability through the chain rule:
During training, all positions can be processed in parallel using a causal mask. During generation, tokens are produced sequentially.
Transformer Encoder
A Transformer encoder has almost the same basic components as a decoder, but its self-attention is not causally masked.
The encoder therefore uses:
Unmasked multi-head self-attention.
Residual connections.
Layer normalization.
Position-wise feed-forward networks.
Repeated encoder blocks.
Because each position can attend to the entire sequence, the encoder produces bidirectional contextual representations.
This is appropriate when the entire input is available, as in:
Encoding a source sentence for translation.
Sentence classification.
Token classification.
Extracting contextual representations from text.
Transformer Encoder–Decoder Architecture
The original Transformer architecture combined an encoder and decoder, particularly for machine translation.
Encoder
The encoder processes the source sequence using unmasked self-attention. Each source position can access every other source position.
For a source sentence such as:
I like pizza.
the encoder produces contextual representations:
These representations contain information about the source words and their relationships.
Decoder Self-Attention
The decoder generates the target sequence using masked self-attention. It can access previously generated target words but not future target words.
If the target sequence is generated left to right, the decoder may use:
Previously generated target tokens.
The current target position.
The encoded source sentence.
Cross-Attention
The decoder also contains a second attention operation called cross-attention.
Cross-attention differs from self-attention because its queries and its keys and values come from different sequences:
Queries come from the decoder.
Keys come from the encoder.
Values come from the encoder.
If zi is a decoder representation and hj is an encoder representation, then:
The decoder then computes attention from its current state to all encoder positions:
where:
This allows each target word to selectively consult the entire source sentence.
For machine translation, when generating a target word, the decoder can attend to the source words that are most relevant to that translation decision.
Why Transformers Were Successful
Parallel Computation
Unlike RNNs, Transformers do not require a recurrent step for every sequence position.
During training:
All word embeddings can be processed simultaneously.
All query, key, and value projections can be computed using matrix multiplication.
All pairwise attention scores can be calculated in parallel.
GPUs can be used much more effectively.
This greatly improves training efficiency.
Better Long-Distance Interactions
In self-attention, any two positions can interact in a single attention operation.
The computational path between distant words is therefore much shorter than in an RNN. A word can directly attend to another word even if many tokens occur between them.
This improves the model’s ability to learn:
Long-distance syntactic dependencies.
Coreference relationships.
Semantic relationships across sentences.
Document-level associations, when the sequence fits within the model’s context window.
Strong Performance
Transformers achieved strong results in machine translation and other sequence-to-sequence tasks. Their advantage was not only accuracy:
They were more parallelizable.
They could train efficiently on large datasets.
They could take better advantage of large GPU systems.
They scaled effectively with additional computation and data.
This scalability helped Transformers become the dominant architecture for many modern NLP systems.
They also enabled large-scale pretraining, in which a model learns from vast amounts of text before being adapted to particular tasks.
Limitations of Transformers
Quadratic Sequence-Length Cost
Self-attention computes an interaction score for every pair of positions. For a sequence of length n, the attention score matrix has shape:
Therefore, the memory and computation associated with pairwise attention grow approximately as:
This is called the quadratic sequence-length problem.
For a short sequence, the cost is manageable. For a very long sequence, the number of pairwise interactions becomes enormous.
For example:
A sequence of length 30 requires roughly 302 pairwise interactions.
A sequence of length 50,000 requires roughly 50,0002 pairwise interactions.
Long documents, books, and entire large web pages can therefore be difficult to process in a single Transformer context.
Context-Length Limitations
Learned position embeddings may impose a maximum sequence length. Even when position representations are not the main limitation, the quadratic cost of attention often forces models to use a finite context window.
This creates practical difficulties when attempting to:
Fit a long prompt into a language model.
Process an entire novel.
Encode a complete Wikipedia article.
Maintain information across very long documents.
Efficient-Attention Research
Many variants attempt to reduce the quadratic cost by approximating or restricting attention, for example by:
Limiting attention to local windows.
Using sparse attention patterns.
Projecting representations into lower-dimensional spaces.
Approximating all-pairs interactions.
Compressing or summarizing context.
However, in large modern language models, the feed-forward components may account for a substantial portion of the computation. As a result, whether eliminating all quadratic attention computation is always necessary remains an active research question.
Position Representation Challenges
Absolute word indices are not always the most meaningful representation of position. A word’s useful positional information may instead involve:
Its distance from another word.
Whether it occurs before or after another word.
Its location in a syntactic dependency structure.
Its position relative to a sentence or document boundary.
Developing more flexible and linguistically useful position representations remains an important area of research.
Overall Conceptual Summary
Self-attention allows every sequence position to retrieve relevant information from every other position using learned query, key, and value representations.
Transformers combine self-attention with positional information, multi-head attention, feed-forward networks, residual connections, layer normalization, and—when necessary—causal masking.
The main advantages over recurrent models are:
Direct interaction between distant positions.
Highly parallelizable computation.
Strong scalability with data and compute.
Effective modeling of contextual and long-distance relationships.
Support for both bidirectional encoding and autoregressive decoding.
The main costs and limitations are:
Quadratic computation and memory in sequence length.
Finite context windows.
The need to explicitly represent sequence order.
The possibility of redundant or weakly specialized attention heads.
Continued difficulty processing very long documents efficiently.
Transformers became dominant because their parallelism and scalability made it practical to train much larger models on much larger datasets than was generally feasible with recurrent architectures.

Ask anything
We've read this whole study set, so questions about it get the best answers.