1. Home
  2. Explore
  3. Computer Science
  4. Self-Attention and Transformers

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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:

  1. A bidirectional LSTM reads the source sentence from both directions.
  2. The encoder produces contextual representations of the source words.
  3. A unidirectional LSTM generates the translated sentence one word at a time.
  4. 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→⋯→hth_1 \rightarrow h_2 \rightarrow h_3 \rightarrow \cdots \rightarrow h_th1​→h2​→h3​→⋯→ht​

Consequently, 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 ttt cannot be calculated until the hidden state at position t−1t-1t−1 is available:

ht=f(ht−1,xt)h_t = f(h_{t-1}, x_t)ht​=f(ht−1​,xt​)

Even if a GPU has enough capacity to perform many operations at once, it cannot compute h5h_5h5​ before h4h_4h4​, or h4h_4h4​ before h3h_3h3​.

For a sequence of length nnn, this creates approximately nnn 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→value\text{key} \rightarrow \text{value}key→value

An exact lookup compares a query against keys and selects one matching value. Attention performs a softer version:

  1. Compare the query with every key.
  2. Assign a similarity score to each key.
  3. Convert the scores into weights using a softmax.
  4. 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,…,sns_1, s_2, \ldots, s_ns1​,s2​,…,sn​ with the keys. The attention weights are:

αj=exp⁡(sj)∑j′=1nexp⁡(sj′)\alpha_j = \frac{\exp(s_j)}{\sum_{j'=1}^{n} \exp(s_{j'})}αj​=∑j′=1n​exp(sj′​)exp(sj​)​

Each αj\alpha_jαj​ lies between 000 and 111, and all the weights sum to 111:

∑j=1nαj=1\sum_{j=1}^{n} \alpha_j = 1j=1∑n​αj​=1

The resulting attention output is a weighted sum of the values:

o=∑j=1nαjvjo = \sum_{j=1}^{n} \alpha_j v_jo=j=1∑n​αj​vj​

A 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,…,wnw_1, w_2, \ldots, w_nw1​,w2​,…,wn​. Each word is first mapped to a non-contextual embedding:

xi=Ewix_i = E w_ixi​=Ewi​

Here:

  • EEE is an embedding matrix.
  • wiw_iwi​ can be represented as a one-hot vector for the word at position iii.
  • xix_ixi​ is a vector of dimensionality DDD.
  • The embedding xix_ixi​ depends on the word identity but not yet on its context.

Each embedding is then transformed three different ways:

qi=xiWQq_i = x_i W^Qqi​=xi​WQ ki=xiWKk_i = x_i W^Kki​=xi​WK vi=xiWVv_i = x_i W^Vvi​=xi​WV

The three resulting vectors have different roles:

  • The query qiq_iqi​ represents what position iii is looking for.
  • The key kjk_jkj​ represents what position jjj contains or offers for matching.
  • The value vjv_jvj​ contains the information that position jjj can contribute.

The query at position iii is compared with every key. A common similarity function is the dot product:

eij=qikj⊤e_{ij} = q_i k_j^\topeij​=qi​kj⊤​

The value eije_{ij}eij​ measures how strongly position iii should attend to position jjj.

The scores are normalized across all possible source positions:

αij=exp⁡(eij)∑j′=1nexp⁡(eij′)\alpha_{ij} = \frac{\exp(e_{ij})} {\sum_{j'=1}^{n}\exp(e_{ij'})}αij​=∑j′=1n​exp(eij′​)exp(eij​)​

The output representation for position iii is then:

oi=∑j=1nαijvjo_i = \sum_{j=1}^{n} \alpha_{ij}v_joi​=j=1∑n​αij​vj​

Thus, 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 WQW^QWQ and WKW^KWK 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 qiq_iqi​ and kik_iki​ 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 iii, the model can compute attention over all positions jjj 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×DX = \begin{bmatrix} x_1\\ x_2\\ \vdots\\ x_n \end{bmatrix} \in \mathbb{R}^{n \times D}X=​x1​x2​⋮xn​​​∈Rn×D

The query, key, and value matrices are computed at once:

Q=XWQQ = XW^QQ=XWQ K=XWKK = XW^KK=XWK V=XWVV = XW^VV=XWV

The matrix QK⊤QK^\topQK⊤ contains every pairwise query-key dot product:

QK⊤∈Rn×nQK^\top \in \mathbb{R}^{n \times n}QK⊤∈Rn×n

The entry in row iii, column jjj is the score eije_{ij}eij​ between query iii and key jjj.

The complete self-attention operation can be written as:

Attention⁡(Q,K,V)=softmax⁡(QK⊤)V\operatorname{Attention}(Q,K,V) = \operatorname{softmax}(QK^\top)VAttention(Q,K,V)=softmax(QK⊤)V

The 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 iii, the model creates a positional vector pip_ipi​ and adds it to the word embedding:

x~i=xi+pi\tilde{x}_i = x_i + p_ix~i​=xi​+pi​

The 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⁡(i100002j/D)p_{i,2j} = \sin\left(\frac{i}{10000^{2j/D}}\right)pi,2j​=sin(100002j/Di​) pi,2j+1=cos⁡(i100002j/D)p_{i,2j+1} = \cos\left(\frac{i}{10000^{2j/D}}\right)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 nnn and the model dimensionality is DDD, the model can learn:

P∈Rn×DP \in \mathbb{R}^{n \times D}P∈Rn×D

The row pip_ipi​ is added to the word embedding at position iii.

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×nn \times nn×n

The number of pairwise interactions therefore grows as:

O(n2)O(n^2)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)+b2\operatorname{FFN}(x) = W_2 \sigma(W_1x+b_1)+b_2FFN(x)=W2​σ(W1​x+b1​)+b2​

Here:

  • W1W_1W1​ and W2W_2W2​ are learned matrices.
  • b1b_1b1​ and b2b_2b2​ are learned bias vectors.
  • σ\sigmaσ 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 iii to position jjj is retained when:

j≤ij \leq ij≤i

If position jjj is in the future, the score is replaced with a very large negative value, conceptually:

eij=−∞when j>ie_{ij} = -\infty \qquad \text{when } j > ieij​=−∞when j>i

After the softmax, this becomes a weight of zero:

softmax⁡(−∞)=0\operatorname{softmax}(-\infty)=0softmax(−∞)=0

Therefore, the representation at position iii cannot use information from positions greater than iii.

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:

  1. Word embeddings.
  2. Positional representations.
  3. Self-attention.
  4. A position-wise feed-forward network.
  5. Mechanisms for masking when future information must be hidden.

These components can be stacked repeatedly:

self-attention→feed-forward→self-attention→feed-forward→⋯\text{self-attention} \rightarrow \text{feed-forward} \rightarrow \text{self-attention} \rightarrow \text{feed-forward} \rightarrow \cdotsself-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 HHH attention heads, the model learns separate query, key, and value transformations for each head:

WhQ,WhK,WhVfor h=1,…,HW_h^Q,\quad W_h^K,\quad W_h^V \qquad \text{for } h=1,\ldots,HWhQ​,WhK​,WhV​for h=1,…,H

Each head projects the input into a lower-dimensional space, often of dimensionality:

DH\frac{D}{H}HD​

The hhhth head computes:

head⁡h=Attention⁡(XWhQ,XWhK,XWhV)\operatorname{head}_h = \operatorname{Attention} \left( XW_h^Q, XW_h^K, XW_h^V \right)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⁡(head⁡1,…,head⁡H)WO\operatorname{MultiHead}(X) = \operatorname{Concat} \left( \operatorname{head}_1,\ldots,\operatorname{head}_H \right) W^OMultiHead(X)=Concat(head1​,…,headH​)WO

The final matrix WOW^OWO 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⁡(QK⊤dk)V\operatorname{Attention}(Q,K,V) = \operatorname{softmax} \left( \frac{QK^\top}{\sqrt{d_k}} \right)VAttention(Q,K,V)=softmax(dk​​QK⊤​)V

Here, dkd_kdk​ 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)F(x)F(x), the residual version computes:

y=x+F(x)y = x + F(x)y=x+F(x)

In a Transformer, the function FFF 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∈RDx \in \mathbb{R}^Dx∈RD be the representation for one position. Its mean is:

μ=1D∑j=1Dxj\mu = \frac{1}{D} \sum_{j=1}^{D}x_jμ=D1​j=1∑D​xj​

Its variance is:

σ2=1D∑j=1D(xj−μ)2\sigma^2 = \frac{1}{D} \sum_{j=1}^{D}(x_j-\mu)^2σ2=D1​j=1∑D​(xj​−μ)2

The normalized vector is:

x^j=xj−μσ2+ϵ\hat{x}_j = \frac{x_j-\mu} {\sqrt{\sigma^2+\epsilon}}x^j​=σ2+ϵ​xj​−μ​

The small constant ϵ\epsilonϵ prevents division by zero when the variance is extremely small.

Layer normalization may also use learned scale and offset parameters:

yj=γjx^j+βjy_j = \gamma_j \hat{x}_j+\beta_jyj​=γj​x^j​+βj​

where γj\gamma_jγj​ and βj\beta_jβ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:

  1. Apply a sublayer such as self-attention.
  2. Add the sublayer input through a residual connection.
  3. Apply layer normalization.

Conceptually:

AddNorm⁡(x,F)=LayerNorm⁡(x+F(x))\operatorname{AddNorm}(x,F) = \operatorname{LayerNorm}(x+F(x))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:

  1. Masked multi-head self-attention.
  2. Add-and-norm.
  3. A position-wise feed-forward network.
  4. Add-and-norm.

The block can be summarized as:

x→masked multi-head self-attention→add-and-norm→feed-forward network→add-and-normx \rightarrow \text{masked multi-head self-attention} \rightarrow \text{add-and-norm} \rightarrow \text{feed-forward network} \rightarrow \text{add-and-norm}x→masked multi-head self-attention→add-and-norm→feed-forward network→add-and-norm

The 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:

  1. Unmasked multi-head self-attention.
  2. Add-and-norm.
  3. A position-wise feed-forward network.
  4. 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,…,hnh_1,\ldots,h_nh1​,…,hn​ and the decoder representations are z1,…,zmz_1,\ldots,z_mz1​,…,zm​, then the decoder forms queries from the ziz_izi​ vectors:

qi=ziWQq_i = z_i W^Qqi​=zi​WQ

It forms keys and values from the encoder outputs:

kj=hjWKk_j = h_j W^Kkj​=hj​WK vj=hjWVv_j = h_j W^Vvj​=hj​WV

The 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:

  1. Masked self-attention over the target-side sequence.
  2. Cross-attention from the decoder to the encoder.
  3. A position-wise feed-forward network.
  4. 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 nnn, the attention score matrix has n2n^2n2 entries.

If the sequence length increases from nnn to 2n2n2n, the number of pairwise interactions increases from:

n2n^2n2

to:

(2n)2=4n2(2n)^2 = 4n^2(2n)2=4n2

This 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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent