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:
Attention, a neural-network primitive that operates fundamentally on sets of vectors.
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:
An encoder, which processes the input sequence.
A decoder, which generates the output sequence.
The Encoder
At time step t, an RNN receives:
The current input vector xt
The previous hidden state ht−1
It produces a new hidden state ht:
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:
Process “we”
Process “see”
Process “the”
Process “sky”
After the final input token, the encoder’s final hidden state is treated as a context vector, commonly denoted by C.
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−1
The previous decoder hidden state st−1
The context vector C
The decoder then produces:
A new hidden state st
A prediction for the next output token yt
Conceptually:
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 st, and the encoder has produced hidden states:
The model compares the decoder state with every encoder state. This produces one scalar alignment score for each input position:
where et,i measures how relevant encoder state hi is to decoder state st.
One possible implementation concatenates st and hi, then passes their concatenation through a learned linear layer:
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:
The resulting attention weights satisfy:
and
Thus, for each decoder step, the attention weights form a probability distribution over the input positions.
A high value of αt,i indicates that the model is placing substantial attention on encoder state hi.
Step 3: Compute a Context Vector
The attention weights are used to form a weighted sum of the encoder hidden states:
The resulting vector ct is the context vector for decoder time step t.
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 ct 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:
The next output token is then predicted from the decoder state.
The complete process repeats for every output position:
Use the current decoder state as a query.
Compare it with every encoder hidden state.
Convert the scores into attention weights.
Compute a weighted combination of encoder states.
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:
The attention-based model instead produces a sequence of context vectors:
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:
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 s0.
Possible strategies include:
Setting s0 equal to the encoder’s final hidden state
Applying a learned linear projection to the encoder’s final hidden state
Setting s0 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:
Compares the query with all data vectors.
Converts the comparisons into weights.
Computes a weighted combination of the data.
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 q and k, the similarity is:
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:
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×dq be the matrix of query vectors.
K∈Rnk×dk be the matrix of key vectors.
V∈Rnk×dv be the matrix of value vectors.
When dq=dk, all pairwise query–key similarities can be computed with one matrix multiplication:
Here, E contains one score for every query–key pair.
A softmax is applied independently across the keys for each query:
The attention output is then:
Thus, the complete scaled dot-product attention operation is:
The matrix A contains the attention weights, and each output row in Y 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:
Compute similarity with the queries.
Supply the information used to construct the output.
The key–value formulation separates these roles.
Each data vector xi is projected into:
A key vector, used for matching.
A value vector, used for retrieval or output construction.
These projections are learned:
where WK and WV are learned parameter matrices.
The query vectors may come from another source and are usually also projected:
The attention operation then becomes:
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 X, the model computes:
It then applies attention:
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:
Because:
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 H heads, the computation can be represented conceptually as:
where each head is an independent attention computation and WO 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:
Projection: Project inputs into queries, keys, and values.
Similarity computation: Compute query–key similarities.
Value weighting: Combine value vectors using attention weights.
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 n, ordinary self-attention requires computing all pairwise interactions. This gives approximately:
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:
Multi-head self-attention
A residual connection
Layer normalization
A feed-forward network, also called an MLP or FFN
Another residual connection
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:
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:
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:
Causal masking ensures that the prediction at position t cannot use information from positions after t.
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:
Extracted from the image.
Flattened or otherwise represented.
Projected into a vector.
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:
The image is divided into patches.
Each patch is converted into a vector.
The vectors pass through transformer blocks.
The resulting representations are pooled or summarized.
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:
RNN sequence-to-sequence models compressed an input sequence into one fixed context vector.
Attention removed this bottleneck by allowing the decoder to revisit the entire input at every output step.
The attention mechanism was generalized into a standalone operator using queries, keys, and values.
Self-attention allowed one set of vectors to communicate internally without an RNN.
Multi-head attention increased capacity by learning several relationship patterns in parallel.
Transformers organized self-attention and feed-forward processing into scalable deep-learning blocks.
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.