Self-Attention and Transformers
Self-Attention and Transformer Networks
Modern natural language processing systems rely heavily on self-attention and Transformer architectures. These methods replaced recurrent neural networks in many major applications because they can connect distant words directly and process many parts of a sequence in parallel.
The central idea is simple:
Self-attention allows each word representation to selectively gather information from other words, regardless of how far away those words are in the sequence.
To understand why this matters, it helps to begin with the recurrent models that came before Transformers.
From Recurrent Neural Networks to Transformers
A common earlier architecture for language tasks used a bidirectional LSTM to encode an input sentence and a unidirectional LSTM to generate an output sequence.
For example, in machine translation:
- A bidirectional LSTM reads the source sentence from both directions.
- The encoder produces contextual representations of the source words.
- A unidirectional LSTM generates the translated sentence one word at a time.
- An attention mechanism gives the decoder access to different parts of the source sentence while generating each target word.
This architecture worked well, but it inherited important limitations from recurrence.
Linear interaction distance
An RNN processes words step by step. If the input is
The chef who went to the store and bought ingredients loves garlic was surprised.
then the relationship between chef and was may be important. However, the recurrent computation must pass through every word between them.
A recurrent network might compute the hidden states in this order:
h1→h2→h3→⋯→htConsequently, information from one word must travel through many intermediate states before affecting a distant word. This is called linear interaction distance: the number of computational steps between two positions grows roughly linearly with the distance between those positions.
Long-distance dependencies are difficult because:
- Information must pass through many transformations.
- Gradients must propagate through many steps during training.
- Even LSTMs, which handle long-range gradients better than simple RNNs, are not perfect.
- The model may struggle to learn that two distant words should interact directly.
The problem resembles a dependency in syntax. In a sentence, words that are syntactically related are not always adjacent. A recurrent network, however, is organized primarily around linear order.
Limited parallelization
Recurrent computation also creates a time dependency. The hidden state at position t cannot be calculated until the hidden state at position t−1 is available:
ht=f(ht−1,xt)Even if a GPU has enough capacity to perform many operations at once, it cannot compute h5 before h4, or h4 before h3.
For a sequence of length n, this creates approximately n sequentially dependent operations. The sequence must effectively be walked through from left to right or right to left.
This is inefficient compared with operations that can be applied to all words simultaneously.
Recurrent networks impose two related constraints: distant words interact through many intermediate steps, and sequence positions must be processed in order.
Why ordinary attention does not completely solve the problem
Attention already helps with the first issue in encoder-decoder models. A decoder can attend directly to any encoder state rather than forcing the entire source sentence into one fixed-size vector.
However, if attention is still placed inside a recurrent decoder, the decoder itself remains sequential. Attention helps the model access distant information, but recurrence still prevents complete parallelization.
Transformers keep the attention idea while removing recurrence from the main sequence-processing operation.
Attention as a Soft Key-Value Lookup
A useful way to understand attention is as a soft lookup in a key-value store.
In an ordinary dictionary:
- A key identifies an entry.
- A query asks for an entry.
- The matching value is returned.
For example, a dictionary might map:
key→valueAn exact lookup compares a query against keys and selects one matching value. Attention performs a softer version:
- Compare the query with every key.
- Assign a similarity score to each key.
- Convert the scores into weights using a softmax.
- Compute a weighted average of the values.
Instead of choosing one key exactly, attention can partially use information from many keys.
Suppose a query has similarity scores s1,s2,…,sn with the keys. The attention weights are:
αj=∑j′=1nexp(sj′)exp(sj)Each αj lies between 0 and 1, and all the weights sum to 1:
j=1∑nαj=1The resulting attention output is a weighted sum of the values:
o=j=1∑nαjvjA large attention weight means that the corresponding value contributes strongly to the output.
Example: representing a word in context
Consider:
I went to Stanford’s CS224N and learned.
To represent learned, the model might attend to:
- Stanford, because the place or institution could affect what was learned.
- CS224N, because it identifies the subject.
- I went, because these words provide grammatical context.
- learned itself, because a word may need to retain some of its own information.
The resulting representation is not simply the original word embedding for learned. It is a context-sensitive combination of information gathered from the entire sentence.
Self-Attention
In self-attention, the queries, keys, and values all come from the same sequence.
Let the sequence contain words w1,w2,…,wn. Each word is first mapped to a non-contextual embedding:
xi=EwiHere:
- E is an embedding matrix.
- wi can be represented as a one-hot vector for the word at position i.
- xi is a vector of dimensionality D.
- The embedding xi depends on the word identity but not yet on its context.
Each embedding is then transformed three different ways:
qi=xiWQ ki=xiWK vi=xiWVThe three resulting vectors have different roles:
- The query qi represents what position i is looking for.
- The key kj represents what position j contains or offers for matching.
- The value vj contains the information that position j can contribute.
The query at position i is compared with every key. A common similarity function is the dot product:
eij=qikj⊤The value eij measures how strongly position i should attend to position j.
The scores are normalized across all possible source positions:
αij=∑j′=1nexp(eij′)exp(eij)The output representation for position i is then:
oi=j=1∑nαijvjThus, each word receives a new representation built from a weighted combination of every word’s value vector.
Why separate query and key transformations?
The matrices WQ and WK allow the model to learn what kinds of relationships matter for matching.
If the same transformation were used everywhere, the model would have less flexibility. Separate transformations allow a word to have one representation for:
- What it is looking for as a query.
- What it offers as a key.
- What information it contributes as a value.
The model can also learn whether a word should attend to itself. If the query and key transformations make qi and ki similar, self-attention may assign substantial weight to the word’s own value. If they make them dissimilar, the model can reduce self-attention.
The Parallelization Advantage of Self-Attention
Self-attention removes the need to process positions one at a time.
For every position i, the model can compute attention over all positions j simultaneously. A word can interact directly with another word whether the two are adjacent or separated by thousands of positions.
Therefore:
- The interaction distance between any two positions is effectively constant in terms of attention steps.
- Long-distance dependencies do not require information to pass through every intervening word.
- The attention computations for all positions can be performed in parallel.
This is the key contrast with recurrence. An RNN builds a chain, while self-attention builds direct connections among all positions.
Self-attention replaces a long sequential path with direct, content-dependent interactions across the sequence.
Think About It
A sentence may contain two words that are far apart but strongly related grammatically. Which architecture gives those words a more direct computational connection: a recurrent chain or a self-attention layer? The answer follows from whether information must pass through intermediate positions.
Computing Self-Attention with Matrices
Although self-attention can be described one word at a time, practical systems compute it using large matrix operations.
Stack all word embeddings into a matrix:
X=x1x2⋮xn∈Rn×DThe query, key, and value matrices are computed at once:
Q=XWQ K=XWK V=XWVThe matrix QK⊤ contains every pairwise query-key dot product:
QK⊤∈Rn×nThe entry in row i, column j is the score eij between query i and key j.
The complete self-attention operation can be written as:
Attention(Q,K,V)=softmax(QK⊤)VThe softmax is applied across each row so that every position receives a probability distribution over the positions it can attend to.
This matrix formulation is efficient for GPUs because it avoids an explicit loop over words. A GPU can perform large matrix multiplications in parallel.
Positional Information
Self-attention has an important weakness: by itself, it does not know the order of the words.
Consider these two sequences:
Zuko made his uncle.
His uncle made Zuko.
The words are identical, but their order and meanings differ. If the initial representations depend only on word identity, the attention operation has no direct information telling it which word appeared first, second, or third.
Self-attention naturally operates on a set of vectors. A set does not have an inherent order, so the model must be given positional information.
Adding position representations
For each position i, the model creates a positional vector pi and adds it to the word embedding:
x~i=xi+piThe combined vector now represents both:
- Which word is present.
- Where that word occurs in the sequence.
The positional information can be added at the input to the network. Once the position is included in the representation, later layers can use it.
Sinusoidal position representations
One early approach used sine and cosine functions with different frequencies across dimensions. A general form is:
pi,2j=sin(100002j/Di) pi,2j+1=cos(100002j/Di)Different dimensions vary with different periods. Some dimensions change rapidly across positions, while others change slowly.
Together, these patterns create a distinctive vector for each position. The use of different frequencies gives the model multiple ways to distinguish positions and potentially reason about relative distances.
However, sinusoidal encodings do not solve every practical problem. They may not generalize perfectly to sequence lengths longer than those seen during training.
Learned position representations
A simpler alternative is to learn a position matrix directly. If the maximum sequence length is n and the model dimensionality is D, the model can learn:
P∈Rn×DThe row pi is added to the word embedding at position i.
This method allows the training process to discover whatever positional patterns are useful. Its limitation is that the model has representations only for the positions included in the learned matrix. A sequence longer than the maximum length may therefore require special handling or cause an error.
Sequence-length limitations
Self-attention also has a computational cost that becomes important for long sequences. Since every position can compare with every other position, the attention score matrix has shape:
n×nThe number of pairwise interactions therefore grows as:
O(n2)This is called quadratic complexity in sequence length. Doubling the sequence length approximately quadruples the number of pairwise attention scores.
As a result, even large language models may have difficulty processing an entire novel, book, or long document in a single attention window.
Feed-Forward Networks
Basic self-attention mainly computes weighted averages. If a model repeatedly applies only this operation, it would continue recombining value vectors without introducing enough nonlinear processing.
Transformers solve this by adding a position-wise feed-forward network after self-attention.
For each position independently, a typical feed-forward network has the form:
FFN(x)=W2σ(W1x+b1)+b2Here:
- W1 and W2 are learned matrices.
- b1 and b2 are learned bias vectors.
- σ is a nonlinear activation function.
- The same feed-forward network parameters are applied to each sequence position.
The self-attention layer mixes information across positions. The feed-forward layer then processes each position’s contextualized representation independently.
This separation is useful:
- Self-attention answers: “Which other positions should this word use?”
- The feed-forward network answers: “How should this word’s gathered information be transformed?”
Feed-forward computations are highly parallelizable because each position can be processed independently.
Think About It
If self-attention gathers information from the whole sentence, what additional role does the feed-forward network provide? It provides nonlinear transformation and processing after the information has been gathered.
Masking Future Positions
For some tasks, especially language modeling and sequence generation, a position must not see future words.
Suppose the model is predicting the next word in:
The chef prepared the meal.
When predicting the word after chef, the model may use the words before or at the current position, but it must not use the actual future answer during training. Otherwise, the model would be given information it would not have when generating text.
Causal masking
The attention score from position i to position j is retained when:
j≤iIf position j is in the future, the score is replaced with a very large negative value, conceptually:
eij=−∞when j>iAfter the softmax, this becomes a weight of zero:
softmax(−∞)=0Therefore, the representation at position i cannot use information from positions greater than i.
A causal attention pattern looks triangular:
- The first position attends only to itself.
- The second position attends to the first and second positions.
- The third position attends to the first, second, and third positions.
- Later positions can attend to all earlier positions but not future positions.
Masking in different architectures
Masking is needed when the model must preserve an information constraint, such as autoregressive generation.
- A language-model decoder uses masked self-attention.
- A translation decoder uses masked self-attention because it generates the target sentence from left to right.
- An encoder reading a complete source sentence usually does not use causal masking because the encoder is allowed to examine the entire source sentence.
- The encoder’s representations can therefore use bidirectional context.
Padding positions can also be masked so that the model does not attend to artificial padding tokens added to make sequences in a batch the same length.
The Minimal Transformer Building Block
A basic self-attention block contains:
- Word embeddings.
- Positional representations.
- Self-attention.
- A position-wise feed-forward network.
- Mechanisms for masking when future information must be hidden.
These components can be stacked repeatedly:
self-attention→feed-forward→self-attention→feed-forward→⋯Each layer builds more sophisticated contextual representations. However, practical Transformers add several important improvements, including multi-head attention, residual connections, layer normalization, and scaled dot products.
Multi-Head Self-Attention
A single attention operation may have difficulty representing several different relationships at once.
For example, when representing a word, the model might need to consider:
- A syntactically related word.
- A nearby adjective or noun.
- A named entity.
- A distant word that establishes topic.
- A word that provides semantic context.
These relationships may require different similarity functions. Multi-head attention addresses this by running several attention operations in parallel.
Separate attention heads
For H attention heads, the model learns separate query, key, and value transformations for each head:
WhQ,WhK,WhVfor h=1,…,HEach head projects the input into a lower-dimensional space, often of dimensionality:
HDThe hth head computes:
headh=Attention(XWhQ,XWhK,XWhV)Each head can learn to focus on different patterns. The heads are not forced to specialize in different ways, but empirical results show that multiple heads are generally more effective than a single head.
Combining the heads
The outputs of all heads are concatenated:
MultiHead(X)=Concat(head1,…,headH)WOThe final matrix WO mixes the information from the different heads.
Although each head works in a smaller dimensional space, the heads together restore the original model dimensionality. The computation can still be performed efficiently by reshaping tensors and using batched matrix operations.
Why multiple heads help
Each head has its own query, key, and value matrices. This means that each head can learn a different way of deciding:
- What information is relevant.
- Which positions should interact.
- What information should be passed forward.
Some heads may learn syntactic patterns, while others may capture semantic or positional relationships. There may be some redundancy, but the overall collection of heads provides greater flexibility than one attention operation.
Scaled Dot-Product Attention
As the dimensionality of the vectors increases, dot products can become large even when the vectors are not meaningfully related.
Large values entering a softmax can make the distribution extremely peaked. For example, one position may receive nearly all the probability while the others receive almost none. In such a saturated softmax, gradients can become very small, making learning more difficult.
The solution is to scale the dot products by the square root of the key dimensionality. The standard operation is:
Attention(Q,K,V)=softmax(dkQK⊤)VHere, dk is the dimensionality of each key and query vector.
Scaling keeps the scores in a more suitable numerical range, particularly at initialization, and helps maintain useful gradients during training.
Residual Connections
Deep networks can be difficult to train because gradients may vanish or because each layer may need to learn a complete transformation from scratch.
A residual connection gives a layer its input directly as an additional path to its output. If a layer computes F(x), the residual version computes:
y=x+F(x)In a Transformer, the function F may be a self-attention layer or a feed-forward layer.
Residual connections help in several ways:
- They provide a direct route for information to move through many layers.
- They provide a direct route for gradients during backpropagation.
- They allow a layer to learn only a useful modification, or residual, rather than an entirely new representation.
- If the learned transformation is initially small, the block behaves approximately like the identity function.
The important intuition is that a layer can preserve its input and add improvements to it.
Layer Normalization
Different layers may produce activations with very different scales. Some values may become unusually large, while others may shrink. Such variation can make optimization unstable or unnecessarily difficult.
Layer normalization standardizes the features within an individual vector.
Let x∈RD be the representation for one position. Its mean is:
μ=D1j=1∑DxjIts variance is:
σ2=D1j=1∑D(xj−μ)2The normalized vector is:
x^j=σ2+ϵxj−μThe small constant ϵ prevents division by zero when the variance is extremely small.
Layer normalization may also use learned scale and offset parameters:
yj=γjx^j+βjwhere γj and βj are learned parameters.
A crucial feature of layer normalization is that normalization is performed independently for each position and each example. It does not compute statistics by combining unrelated examples in the batch. This differs from batch normalization, whose statistics depend on other examples in the batch.
Add-and-norm
Transformer diagrams often combine a residual connection and layer normalization into an add-and-norm operation:
- Apply a sublayer such as self-attention.
- Add the sublayer input through a residual connection.
- Apply layer normalization.
Conceptually:
AddNorm(x,F)=LayerNorm(x+F(x))This structure is used after both attention and feed-forward sublayers.
The Transformer Decoder
A Transformer decoder is built by stacking several decoder blocks.
Each block contains:
- Masked multi-head self-attention.
- Add-and-norm.
- A position-wise feed-forward network.
- Add-and-norm.
The block can be summarized as:
x→masked multi-head self-attention→add-and-norm→feed-forward network→add-and-normThe blocks are repeated several times. The final representations can then be used to predict the next token, classify the input, or perform another task.
A decoder uses causal masking when it must generate a sequence from left to right. During training, all positions can be processed in parallel, but the mask ensures that each position behaves as if it only had access to the past.
This distinction is important: the computation is parallelized, while the information flow remains causal.
The Transformer Encoder
The Transformer encoder has nearly the same block structure as the decoder, but it does not use causal masking when full input context is permitted.
An encoder block contains:
- Unmasked multi-head self-attention.
- Add-and-norm.
- A position-wise feed-forward network.
- Add-and-norm.
Because there is no future-position restriction, every word can attend to every other word in the input.
This gives the encoder bidirectional context. For example, the representation of a word can use both the words before it and the words after it.
The Encoder-Decoder Transformer
The original Transformer architecture combined an encoder and a decoder, especially for tasks such as machine translation.
Encoder
The encoder receives the source sequence and processes it with unmasked self-attention. Every source position can use information from every other source position.
For a source sentence such as:
I like pizza.
the encoder creates contextual representations for all three source words.
Decoder
The decoder generates the target sequence one token at a time. Its first attention operation is masked self-attention over the already generated target tokens.
The decoder then performs a second type of attention called cross-attention.
Cross-attention
In cross-attention:
- The decoder representations provide the queries.
- The encoder representations provide the keys.
- The encoder representations also provide the values.
If the encoder outputs are h1,…,hn and the decoder representations are z1,…,zm, then the decoder forms queries from the zi vectors:
qi=ziWQIt forms keys and values from the encoder outputs:
kj=hjWK vj=hjWVThe decoder can then attend from each target position to all source positions.
This allows the decoder to decide which parts of the source sentence are relevant while generating each target word.
The overall decoder block therefore includes:
- Masked self-attention over the target-side sequence.
- Cross-attention from the decoder to the encoder.
- A position-wise feed-forward network.
- Residual connections and layer normalization around the sublayers.
The distinction is:
- Self-attention: queries, keys, and values come from the same sequence.
- Cross-attention: queries come from one sequence, while keys and values come from another.
Think About It
During translation, why should the decoder use masked self-attention for the target sentence but unmasked attention in the encoder? The encoder may read the complete source sentence, whereas the decoder must not use target words that have not yet been generated.
Why Transformers Became So Important
Transformers offered several major advantages over recurrent architectures:
- Direct interactions between distant positions.
- Efficient parallel computation during training.
- Better use of modern GPU hardware.
- Flexible multi-head representations.
- Strong performance across many language tasks.
- The ability to train effectively on very large datasets.
The first Transformer results were especially notable for machine translation. The improvement was not only about final quality; Transformers were also much more efficient to train because they removed the sequential dependency of recurrent processing.
As models became larger and were trained on more data, Transformer architectures became the dominant foundation for many natural language systems. They also supported the rise of large-scale pretraining, in which a model learns from enormous amounts of text before being adapted to specific tasks.
The combination of:
- Parallelizable computation,
- Large datasets,
- Large models,
- Powerful GPUs,
- Contextual representations,
allowed Transformers to surpass LSTMs in many modern NLP applications.
Limitations and Ongoing Improvements
Transformers are powerful, but they are not perfect.
Quadratic attention cost
The largest limitation discussed is the quadratic cost in sequence length. For a sequence of length n, the attention score matrix has n2 entries.
If the sequence length increases from n to 2n, the number of pairwise interactions increases from:
n2to:
(2n)2=4n2This makes very long contexts expensive in both memory and computation.
Researchers have therefore explored methods that:
- Restrict attention to selected positions.
- Approximate the full attention matrix.
- Map representations into lower-dimensional spaces.
- Use alternative forms of positional information.
- Reduce the number of pairwise interactions.
However, the standard Transformer remains highly competitive, and in many large systems the main computational cost may come from components other than the attention matrix itself.
Positional representations
Absolute position embeddings are not always ideal. The meaning of a position often depends more on relative relationships, such as:
- Whether one word comes before another.
- How many positions separate two words.
- Whether two words are close in a dependency structure.
This has motivated research into relative positional representations and other ways to encode sequence structure.
Architectural variants
Researchers have also experimented with:
- Different activation functions in feed-forward networks.
- Different normalization arrangements.
- Different attention patterns.
- Different positional representations.
- Different numbers of attention heads.
- More efficient long-context mechanisms.
Despite these modifications, the central Transformer design—attention, feed-forward processing, residual connections, and normalization—has remained remarkably durable.
Comprehensive Review
Self-attention was developed as a way for words to interact directly with one another. Unlike an RNN, it does not require information to move sequentially through every intermediate position.
The key ideas are:
- A query represents what a position is looking for.
- A key represents what a position offers for matching.
- A value contains the information that can be retrieved.
- Dot products measure query-key compatibility.
- Softmax converts compatibility scores into attention weights.
- A weighted sum of values creates a contextualized representation.
Self-attention solves the RNN’s linear interaction problem and makes sequence computation much more parallelizable. However, it needs additional components:
- Positional representations provide word order.
- Feed-forward networks add nonlinear processing.
- Causal masks prevent access to future tokens when required.
- Multi-head attention lets the model examine different relationships simultaneously.
- Scaled dot products keep attention scores in a useful numerical range.
- Residual connections improve information and gradient flow.
- Layer normalization stabilizes representations across layers.
A Transformer encoder uses unmasked self-attention to build bidirectional contextual representations. A Transformer decoder uses masked self-attention to generate sequences without seeing future tokens. An encoder-decoder Transformer adds cross-attention, allowing the decoder to query the encoder’s source representations.
Transformers became dominant because they combine direct long-distance interaction with efficient parallel computation. Their primary challenge is the quadratic growth of attention cost with sequence length, but their ability to use large datasets and large-scale computation has made them the foundation of many modern AI systems.

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