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

Study methods

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

Attention and Transformers

Attention and Transformers

From Recurrent Neural Networks to Attention

Recurrent neural networks (RNNs) were introduced as architectures for processing sequences. Unlike a standard feed-forward network, which typically maps one input to one output, an RNN processes a sequence one step at a time while maintaining a hidden state that carries information from earlier steps.

Sequence-processing architectures enable several problem types that are difficult to solve with ordinary feed-forward or convolutional networks:

  • One-to-one: An image is mapped to a single class label.

  • One-to-many: An image is mapped to a sequence of words, as in image captioning.

  • Many-to-one: A sequence of video frames is mapped to one classification.

  • Many-to-many: One sequence is mapped to another sequence, as in machine translation.

The central topics are:

  1. Attention, a neural-network primitive that operates fundamentally on sets of vectors.

  2. Transformers, neural-network architectures built around self-attention.

Transformers are now widely used for large-scale tasks involving:

  • Text classification and generation

  • Image classification and generation

  • Audio processing

  • Machine translation

  • Multimodal learning

  • Other large-data, large-compute deep-learning applications

Although transformers became dominant later, their key ideas developed from earlier work on RNNs and sequence-to-sequence learning.


Sequence-to-Sequence Translation with RNNs

A sequence-to-sequence translation system receives a sequence in one language and produces a sequence in another language.

For example:

  • Input: an English sentence

  • Output: the corresponding Italian sentence

The input and output sequences may differ in:

  • Length

  • Word order

  • Number of words

  • Grammatical structure

Therefore, translation cannot rely on a simple one-to-one correspondence between positions in the two sequences.

Encoder–Decoder Architecture

A traditional RNN sequence-to-sequence model contains two RNNs:

  1. An encoder, which processes the input sequence.

  2. A decoder, which generates the output sequence.

The Encoder

At time step ttt, an RNN receives:

  • The current input vector xtx_txt​

  • The previous hidden state ht−1h_{t-1}ht−1​

It produces a new hidden state hth_tht​:

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

The same recurrent unit is applied repeatedly across the sequence. This allows the model to process sequences of variable length.

For a sentence such as “we see the sky,” the encoder processes each word sequentially:

  1. Process “we”

  2. Process “see”

  3. Process “the”

  4. Process “sky”

After the final input token, the encoder’s final hidden state is treated as a context vector, commonly denoted by CCC.

The context vector is intended to summarize the information contained in the entire input sequence.

The recurrent structure causes the final hidden state to depend indirectly on all preceding inputs. Consequently, the model attempts to encode the entire sentence into one vector.

The Decoder

The decoder is another RNN, generally with its own learned parameters. At every output time step, it uses:

  • The previous output token yt−1y_{t-1}yt−1​

  • The previous decoder hidden state st−1s_{t-1}st−1​

  • The context vector CCC

The decoder then produces:

  • A new hidden state sts_tst​

  • A prediction for the next output token yty_tyt​

Conceptually:

st=g(yt−1,st−1,C)s_t = g(y_{t-1}, s_{t-1}, C)st​=g(yt−1​,st−1​,C)

The decoder generates the translated sentence one token at a time.


The Fixed-Length Context Bottleneck

The encoder–decoder architecture creates a serious limitation: the entire input sequence must be compressed into a single fixed-length vector.

This is manageable for short sentences. A vector containing, for example, 128 or 1,024 numbers may plausibly summarize a short sentence. However, the vector size remains fixed even when the input becomes much longer.

For a paragraph, book, or large corpus, the model must still force all information through the same fixed-size vector. This creates a communication bottleneck between the encoder and decoder.

Consequences of the Bottleneck

  • Information may be lost during compression.

  • Important details from early in the input may be difficult to preserve.

  • Longer sequences become increasingly difficult to summarize.

  • The decoder cannot directly access individual encoder states.

  • The model’s capacity does not grow naturally with input length.

The key idea behind attention is therefore:

Instead of forcing the decoder to rely on one fixed context vector, allow it to look back at the entire encoded input whenever it generates an output.

This eliminates the single-vector bottleneck.


Attention in Sequence-to-Sequence Models

The Basic Intuition

At every decoder time step, the model should be able to determine which parts of the input sequence are most relevant to the output it is currently producing.

For example, while generating the translated equivalent of “we see,” the decoder should emphasize the encoder representations associated with “we” and “see.” When generating the equivalent of “sky,” it should emphasize “sky” instead.

The model does not receive explicit supervision indicating which input words correspond to which output words. Instead, it learns how to use attention through the ordinary end-to-end translation objective.


Step 1: Compute Alignment Scores

Suppose the decoder has a current hidden state sts_tst​, and the encoder has produced hidden states:

h1,h2,…,hnh_1, h_2, \ldots, h_nh1​,h2​,…,hn​

The model compares the decoder state with every encoder state. This produces one scalar alignment score for each input position:

et,i=fatt(st,hi)e_{t,i} = f_{\text{att}}(s_t, h_i)et,i​=fatt​(st​,hi​)

where et,ie_{t,i}et,i​ measures how relevant encoder state hih_ihi​ is to decoder state sts_tst​.

One possible implementation concatenates sts_tst​ and hih_ihi​, then passes their concatenation through a learned linear layer:

et,i=w⊤[st;hi]+be_{t,i} = w^\top [s_t;h_i] + bet,i​=w⊤[st​;hi​]+b

The exact alignment function can vary, but its output is a scalar.


Step 2: Convert Alignment Scores into Attention Weights

Raw alignment scores are arbitrary real values. They are converted into normalized attention weights with a softmax:

αt,i=exp⁡(et,i)∑j=1nexp⁡(et,j)\alpha_{t,i} = \frac{\exp(e_{t,i})} {\sum_{j=1}^{n}\exp(e_{t,j})}αt,i​=∑j=1n​exp(et,j​)exp(et,i​)​

The resulting attention weights satisfy:

0≤αt,i≤10 \leq \alpha_{t,i} \leq 10≤αt,i​≤1

and

∑i=1nαt,i=1\sum_{i=1}^{n}\alpha_{t,i}=1∑i=1n​αt,i​=1

Thus, for each decoder step, the attention weights form a probability distribution over the input positions.

A high value of αt,i\alpha_{t,i}αt,i​ indicates that the model is placing substantial attention on encoder state hih_ihi​.


Step 3: Compute a Context Vector

The attention weights are used to form a weighted sum of the encoder hidden states:

ct=∑i=1nαt,ihic_t = \sum_{i=1}^{n}\alpha_{t,i}h_ict​=∑i=1n​αt,i​hi​

The resulting vector ctc_tct​ is the context vector for decoder time step ttt.

Unlike the original sequence-to-sequence model, the context vector is no longer computed once for the entire sequence. It is recomputed at every decoder step.

Each ctc_tct​ is therefore a different summary of the input, tailored to the output currently being generated.


Step 4: Generate the Next Output

The decoder uses the new context vector along with its previous state and the previous output token:

st+1=g(yt,st,ct)s_{t+1} = g(y_t, s_t, c_t)st+1​=g(yt​,st​,ct​)

The next output token is then predicted from the decoder state.

The complete process repeats for every output position:

  1. Use the current decoder state as a query.

  2. Compare it with every encoder hidden state.

  3. Convert the scores into attention weights.

  4. Compute a weighted combination of encoder states.

  5. Use the resulting context vector to generate the next output.

This allows the decoder to revisit the entire input sequence repeatedly.


Why Attention Solves the Bottleneck

The original encoder–decoder model used one fixed context vector:

CCC

The attention-based model instead produces a sequence of context vectors:

c1,c2,…,cmc_1, c_2, \ldots, c_mc1​,c2​,…,cm​

where each context vector is adapted to a different output position.

This provides several advantages:

  • The input is not compressed into a single vector.

  • The decoder can access information from any input position.

  • Different output tokens can focus on different input tokens.

  • Long sequences are easier to process.

  • The model can learn useful input–output alignments.

Attention also creates a soft form of interpretability. By examining the attention weights, one can see which input elements received the most weight while producing each output.


Attention Is Learned End to End

The attention mechanism is entirely differentiable:

  • Alignment functions are differentiable.

  • Softmax is differentiable.

  • Weighted sums are differentiable.

  • The decoder and output loss are differentiable.

The model is trained using the usual sequence prediction objective, such as cross-entropy loss:

L=−∑tlog⁡p(yt∣y<t,x)\mathcal{L} = -\sum_t \log p(y_t \mid y_{<t}, x)L=−∑t​logp(yt​∣y<t​,x)

The model is not explicitly told which input words align with which output words. Instead, gradient descent adjusts the parameters so that the learned attention patterns help minimize the output prediction loss.

This is important because manually labeling alignments for every input–output pair would be expensive and difficult.


Initializing the Decoder

The word “initialization” can refer to two different things.

Initializing Decoder Parameters

The decoder’s learned weights must be initialized before training. They are typically initialized randomly and then optimized through gradient descent.

Initializing the Decoder Hidden State

When processing a new output sequence, the decoder also needs an initial hidden state s0s_0s0​.

Possible strategies include:

  • Setting s0s_0s0​ equal to the encoder’s final hidden state

  • Applying a learned linear projection to the encoder’s final hidden state

  • Setting s0s_0s0​ to an all-zero vector

Any of these can work if the rest of the model is trained consistently with that choice.


Visualizing Attention

Attention weights can be visualized in a two-dimensional matrix.

  • Columns correspond to input tokens.

  • Rows correspond to output tokens.

  • Each matrix entry contains the attention weight assigned to one input token while producing one output token.

For an English-to-French translation, the matrix may show patterns such as:

Diagonal Patterns

A diagonal structure indicates that input and output words largely correspond in the same order.

For example, if the first four English words align with the first four French words, the attention matrix will contain a diagonal band in that region.

Reversed or Non-Diagonal Patterns

A backward diagonal or another non-diagonal pattern indicates that the model has learned a different word order between the two languages.

Block Patterns

A small rectangular block can indicate that several input words correspond collectively to several output words rather than forming a clean one-to-one alignment.

Attention visualizations can therefore reveal that the model has learned:

  • Word correspondences

  • Reordering between languages

  • Groupings of words

  • Some grammatical structure

The model is not explicitly given grammar rules. It learns useful regularities because the architecture provides a mechanism for relating input and output elements, and gradient descent discovers how to use that mechanism.


Attention as a General Neural-Network Operator

Attention was first motivated as a way to improve RNNs, but the operation is more general than the recurrent architecture in which it originally appeared.

The attention operator can be separated from the RNN and treated as an independent neural-network layer.

Data Vectors, Query Vectors, and Output Vectors

The attention mechanism contains three conceptual components:

  • Data vectors: Represent information that should be summarized. In the original RNN example, these are encoder hidden states.

  • Query vectors: Represent what the model is currently trying to produce or retrieve. In the RNN example, these are decoder hidden states.

  • Output vectors: Summaries of the data vectors, computed specifically for each query.

For every query vector, the attention operator:

  1. Compares the query with all data vectors.

  2. Converts the comparisons into weights.

  3. Computes a weighted combination of the data.

  4. Produces one output vector.

The operator does not need to know where the query vectors came from. They could be produced by an RNN, convolutional network, transformer layer, or another model.


Scaled Dot-Product Attention

Dot Products as Similarity Scores

In principle, the similarity function could be any function that takes two vectors and produces a scalar. A simple and efficient choice is the dot product.

For vectors qqq and kkk, the similarity is:

q⊤kq^\top kq⊤k

A larger dot product generally indicates greater alignment between the vectors.

However, large vector dimensions create a scaling problem. As the dimension increases, the magnitude of dot products tends to increase. Feeding increasingly large scores into the softmax can make the distribution excessively concentrated and may produce poor or vanishing gradients.

To address this, the dot product is divided by the square root of the key dimension:

score⁡(q,k)=q⊤kdk\operatorname{score}(q,k) = \frac{q^\top k}{\sqrt{d_k}}score(q,k)=dk​​q⊤k​

This is called scaled dot-product attention.

The scaling factor:

  • Keeps scores in a more stable range.

  • Prevents the softmax from becoming too sharply concentrated.

  • Improves gradient flow.

  • Makes the architecture more stable as vector dimensions grow.


Matrix Form for Multiple Queries

Processing one query at a time is inefficient. Attention can process many queries in parallel using matrices.

Let:

  • Q∈Rnq×dqQ \in \mathbb{R}^{n_q \times d_q}Q∈Rnq​×dq​ be the matrix of query vectors.

  • K∈Rnk×dkK \in \mathbb{R}^{n_k \times d_k}K∈Rnk​×dk​ be the matrix of key vectors.

  • V∈Rnk×dvV \in \mathbb{R}^{n_k \times d_v}V∈Rnk​×dv​ be the matrix of value vectors.

When dq=dkd_q=d_kdq​=dk​, all pairwise query–key similarities can be computed with one matrix multiplication:

E=QK⊤dkE = \frac{QK^\top}{\sqrt{d_k}}E=dk​​QK⊤​

Here, EEE contains one score for every query–key pair.

A softmax is applied independently across the keys for each query:

A=softmax⁡(QK⊤dk)A = \operatorname{softmax}\left( \frac{QK^\top}{\sqrt{d_k}} \right)A=softmax(dk​​QK⊤​)

The attention output is then:

Y=AVY = AVY=AV

Thus, the complete scaled dot-product attention 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

The matrix AAA contains the attention weights, and each output row in YYY is a weighted combination of the value vectors.


Keys, Queries, and Values

Why Separate Keys from Values?

In the original attention formulation, the same encoder vectors were used both to:

  1. Compute similarity with the queries.

  2. Supply the information used to construct the output.

The key–value formulation separates these roles.

Each data vector xix_ixi​ is projected into:

  • A key vector, used for matching.

  • A value vector, used for retrieval or output construction.

These projections are learned:

K=XWKK = XW_KK=XWK​
V=XWVV = XW_VV=XWV​

where WKW_KWK​ and WVW_VWV​ are learned parameter matrices.

The query vectors may come from another source and are usually also projected:

Q=QinputWQQ = Q_{\text{input}}W_QQ=Qinput​WQ​

The attention operation then becomes:

Y=softmax⁡(QK⊤dk)VY = \operatorname{softmax} \left( \frac{QK^\top}{\sqrt{d_k}} \right)VY=softmax(dk​​QK⊤​)V

Interpretation

  • The query represents what the model is looking for.

  • The key represents how each item can be matched.

  • The value represents the information returned when an item is selected.

A search engine provides an intuitive analogy:

  • A user’s search phrase acts like a query.

  • Indexed representations act like keys.

  • The retrieved search results act like values.

The key and value can encode different aspects of the same underlying data. The key helps determine relevance, while the value supplies the information passed to the output.

The model learns the key and value projections through gradient descent. It is not manually instructed which features should be used for matching or retrieval.


Cross-Attention

A cross-attention layer receives two distinct sets of vectors:

  • Queries from one source

  • Keys and values derived from another source

For example, in machine translation:

  • Decoder states provide the queries.

  • Encoder states provide the keys and values.

Cross-attention is useful whenever one type of data needs to retrieve information from another type of data.

Applications include:

  • Machine translation

  • Image captioning

  • Text-to-image systems

  • Multimodal models

  • Question answering over documents

  • Audio-to-text processing

The number and nature of the query vectors do not need to match those of the data vectors. Each query can independently summarize the external data.


Self-Attention

Definition

A self-attention layer uses one set of input vectors to generate the queries, keys, and values.

Given input vectors XXX, the model computes:

Q=XWQQ = XW_QQ=XWQ​
K=XWKK = XW_KK=XWK​
V=XWVV = XW_VV=XWV​

It then applies attention:

Y=softmax⁡(QK⊤dk)VY = \operatorname{softmax} \left( \frac{QK^\top}{\sqrt{d_k}} \right)VY=softmax(dk​​QK⊤​)V

Each output vector can therefore incorporate information from every input vector.

Cross-Attention Versus Self-Attention

Cross-attention

  • Uses two distinct sources of information.

  • Queries come from one set.

  • Keys and values come from another set.

  • Useful when one representation needs to retrieve information from another.

Self-attention

  • Uses one input set.

  • Queries, keys, and values are all derived from that same set.

  • Useful when elements within one representation need to interact.

  • Common in language, vision, audio, and multimodal models.


Permutation Equivariance

Self-attention has an important structural property: permutation equivariance.

Suppose the input vectors are shuffled. Because queries, keys, and values are computed independently from each input vector, the resulting queries, keys, and values are shuffled in the same way.

The pairwise similarity scores are also rearranged consistently. The softmax and weighted sums preserve this correspondence. Therefore, the outputs are the same vectors as before, but shuffled in the same way as the inputs.

In other words:

Reordering the inputs reorders the outputs correspondingly; it does not otherwise change the computed representations.

This means that self-attention, by itself, does not inherently know whether one vector came before or after another. It fundamentally operates on a set of vectors, even though those vectors are often stored in a matrix or sequence.


Positional Embeddings

Order is essential for many tasks, especially language. The meanings of:

  • “dog bites man”

  • “man bites dog”

are different because the word order is different.

Since self-attention does not automatically encode order, models often add a positional embedding to each input vector. A positional embedding communicates information such as:

  • This vector occurs at position 1.

  • This vector occurs at position 2.

  • This vector occurs at position 3.

The positional information may be learned or generated using a fixed mathematical scheme. It is combined with the input representation before attention is applied.

Positional embeddings allow a model to use the flexibility of self-attention while still reasoning about sequence order.


Masked Self-Attention

In ordinary self-attention, every input vector can attend to every other input vector. Some tasks require restricting these interactions.

Causal Masking

In autoregressive language modeling, the model predicts the next token from previous tokens. It must not access future tokens during training, because that would allow it to cheat.

For a sequence such as:

“attention is very cool”

the model should obey rules such as:

  • The first output can depend only on the first token.

  • The second output can depend on the first two tokens.

  • The third output can depend on the first three tokens.

  • No output can depend on tokens that occur later.

This is implemented using masked self-attention.

How the Mask Works

After calculating the alignment scores, forbidden query–key pairs are assigned a score of negative infinity:

ei,j={ei,j,if attention is permitted−∞,if attention is blockede_{i,j} = \begin{cases} e_{i,j}, & \text{if attention is permitted} \\ -\infty, & \text{if attention is blocked} \end{cases}ei,j​={ei,j​,−∞,​if attention is permittedif attention is blocked​

Because:

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

the corresponding attention weights become zero. The output cannot depend on those value vectors.

Masked self-attention therefore controls which positions may exchange information.


Multi-Head Self-Attention

Motivation

A single attention operation may learn one pattern of relationships among the input vectors. A more expressive model can run several independent attention operations in parallel.

This is called multi-head self-attention.

Each head has:

  • Its own query projection

  • Its own key projection

  • Its own value projection

  • Its own learned parameters

The architecture and computation are the same for every head, but the weights differ. As a result, different heads can learn different types of relationships.

Possible patterns include:

  • Local relationships between neighboring words

  • Long-range grammatical dependencies

  • Agreement between subjects and verbs

  • Correspondence between image regions

  • Different semantic or syntactic relationships

The outputs of the heads are combined and passed through an additional learned output projection.

If there are HHH heads, the computation can be represented conceptually as:

MultiHead⁡(X)=Concat⁡(head⁡1,…,head⁡H)WO\operatorname{MultiHead}(X) = \operatorname{Concat} (\operatorname{head}_1,\ldots,\operatorname{head}_H)W_OMultiHead(X)=Concat(head1​,…,headH​)WO​

where each head is an independent attention computation and WOW_OWO​ mixes information across heads.


Efficient Implementation

Although multi-head attention appears to involve many separate operations, it can be implemented efficiently using matrix multiplication.

A typical implementation contains four major matrix-multiplication stages:

  1. Projection: Project inputs into queries, keys, and values.

  2. Similarity computation: Compute query–key similarities.

  3. Value weighting: Combine value vectors using attention weights.

  4. Output projection: Mix the outputs from the different heads.

The query, key, and value projections can often be fused into one larger matrix multiplication. This is efficient because modern hardware is highly optimized for large matrix operations.

Batched matrix multiplication enables all heads and all sequence positions to be processed in parallel rather than with explicit sequential loops.


Comparing Sequence-Processing Primitives

Recurrent Neural Networks

RNNs operate on ordered one-dimensional sequences.

Strengths

  • Naturally represent sequence order.

  • Maintain a recurrent state.

  • Can process variable-length sequences.

Limitations

  • Each state depends on the previous state.

  • Computation is fundamentally sequential across the sequence.

  • They are difficult to parallelize.

  • Long-range information must pass through many recurrent steps.

  • Scaling to very large models is difficult.


Convolution

Convolution operates on multidimensional grids, including:

  • One-dimensional signals

  • Two-dimensional images

  • Three-dimensional data

  • Higher-dimensional structured inputs

Convolution mixes information locally through a sliding kernel.

Strengths

  • Highly parallelizable across spatial or temporal positions.

  • Efficient for local patterns.

  • Well suited to grid-structured data.

Limitations

  • A single convolutional layer has a limited receptive field.

  • Capturing long-range relationships may require:

    • Very large kernels, or

    • Many stacked convolutional layers

  • Stacking many layers introduces additional sequential depth.


Self-Attention

Self-attention operates on sets of vectors.

Strengths

  • Every vector can interact directly with every other vector in one layer.

  • Naturally handles long-range relationships.

  • Is highly parallelizable.

  • Can be implemented largely with matrix multiplications.

  • Works with many types of data, including text, images, and audio.

  • Does not require a recurrent bottleneck.

Limitation

For a sequence of length nnn, ordinary self-attention requires computing all pairwise interactions. This gives approximately:

O(n2)O(n^2)O(n2)

time and memory costs in the sequence length.

For very long sequences, such as those containing hundreds of thousands or millions of elements, the quadratic cost can become expensive.

However, the high computational cost also means that the model performs substantial interaction and processing. In large-scale deep learning, additional computation can increase model capacity and quality, provided sufficient hardware is available.


Why Parallelizability Matters

Modern hardware scaling increasingly depends on using many processors simultaneously rather than making one processor indefinitely faster.

An algorithm that can use:

  • Several processors

  • Hundreds of processors

  • Thousands of processors

  • Large GPU clusters

can scale to much larger computations.

RNNs are difficult to distribute across sequence positions because each step depends on the preceding step. Self-attention, by contrast, can process all pairwise interactions through large matrix multiplications, which GPUs and distributed systems can execute efficiently.

Thus, parallelizability is a major reason self-attention became so important.


Transformer Architecture

A transformer is a neural-network architecture centered on self-attention.

Transformer Block

A typical transformer block contains:

  1. Multi-head self-attention

  2. A residual connection

  3. Layer normalization

  4. A feed-forward network, also called an MLP or FFN

  5. Another residual connection

  6. Another layer normalization

The architecture can be understood as combining two complementary operations.

Self-Attention

Self-attention allows all vectors to communicate with one another. It performs relational processing:

  • Which tokens are relevant to each other?

  • Which image patches should interact?

  • Which parts of an input provide useful context?

Feed-Forward Network

The feed-forward network processes each vector independently. It performs per-vector transformation after the vectors have exchanged information through attention.

A typical FFN has two learned linear transformations with a nonlinear activation between them:

FFN⁡(x)=W2 σ(W1x+b1)+b2\operatorname{FFN}(x) = W_2\,\sigma(W_1x+b_1)+b_2FFN(x)=W2​σ(W1​x+b1​)+b2​

The combination is powerful:

  • Self-attention mixes information across positions.

  • The FFN transforms each position’s representation independently.

Residual Connections

Residual connections add a layer’s input to its output:

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

They help information and gradients flow through deep networks and make optimization more stable.

Layer Normalization

Layer normalization normalizes the features within each representation. It helps stabilize activations and supports reliable training in deep architectures.

A transformer is built by stacking many transformer blocks.


Scaling Transformers

The basic transformer design has remained relatively stable while its size has increased substantially.

Larger transformers can have:

  • More transformer blocks

  • Larger hidden representations

  • More attention heads

  • More parameters

  • More training data

  • More computation

The same general architecture can therefore scale from relatively small models to models with hundreds of blocks and extremely large parameter counts.

This ability to scale efficiently is one of the main reasons transformers became the dominant architecture for many state-of-the-art applications.


Transformers for Language

For language modeling, text is converted into a sequence of token vectors. The transformer processes these vectors using masked self-attention when the task is autoregressive generation.

At each position, the model produces a representation that can depend on allowed earlier tokens. A prediction layer then converts the representation into probabilities over the vocabulary.

For next-token prediction, the model learns:

p(xt∣x1,…,xt−1)p(x_t \mid x_1,\ldots,x_{t-1})p(xt​∣x1​,…,xt−1​)

Causal masking ensures that the prediction at position ttt cannot use information from positions after ttt.

Transformers replace the recurrent computation of an RNN with parallel attention-based processing during training, while retaining the ability to model relationships across long sequences.


Transformers for Images

Transformers can also process images.

Image Patches

A common approach divides an image into fixed-size patches. Each patch is:

  1. Extracted from the image.

  2. Flattened or otherwise represented.

  3. Projected into a vector.

  4. Treated as one input element to the transformer.

The resulting patch vectors form a set or sequence of visual tokens.

Self-attention allows every image patch to interact with every other patch. This gives the model a direct way to model global relationships across an image.

Image Classification

For image classification:

  1. The image is divided into patches.

  2. Each patch is converted into a vector.

  3. The vectors pass through transformer blocks.

  4. The resulting representations are pooled or summarized.

  5. A linear layer produces class scores.

The transformer can produce one output representation for each input patch. A pooling operation combines these representations into a global representation for classification.

The same general mechanism can be adapted to image generation, segmentation, and other visual tasks.


Key Takeaways

Attention allows a model to dynamically select and combine information from a set of vectors based on a query.

Self-attention generates queries, keys, and values from the same input set, allowing every input element to interact with every other element.

Transformers use multi-head self-attention, residual connections, normalization, and feed-forward networks as their central architecture.

The progression from RNNs to transformers can be summarized as follows:

  1. RNN sequence-to-sequence models compressed an input sequence into one fixed context vector.

  2. Attention removed this bottleneck by allowing the decoder to revisit the entire input at every output step.

  3. The attention mechanism was generalized into a standalone operator using queries, keys, and values.

  4. Self-attention allowed one set of vectors to communicate internally without an RNN.

  5. Multi-head attention increased capacity by learning several relationship patterns in parallel.

  6. Transformers organized self-attention and feed-forward processing into scalable deep-learning blocks.

  7. The resulting architecture can process language, images, audio, and many other forms of data.

Attention is flexible, differentiable, and highly parallelizable. Its main computational cost is the quadratic number of pairwise interactions, but its ability to model long-range relationships and exploit modern parallel hardware has made it one of the most important primitives in contemporary deep learning.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent