Attention and Transformers
Attention and Transformers: From Sequence Bottlenecks to Modern Neural Networks
Modern neural networks often need to process information that is not a single fixed-size object. Text is a sequence of words, audio is a sequence of sound measurements, and video is a sequence of image frames. Attention and transformers provide powerful ways to process these structures by allowing different parts of the input to interact directly.
The key idea is simple:
Attention allows a model to decide which pieces of information are most relevant when producing each output.
Transformers build an entire neural-network architecture around this idea. They are highly parallelizable, flexible, and capable of processing many kinds of data, including language, images, audio, and multimodal inputs.
1. Why Sequence Models Matter
Earlier neural-network architectures often focused on one-to-one problems. A single input produces a single output. For example:
- An image is input to a classifier.
- The classifier outputs a label such as “cat” or “car.”
- A fixed-size feature vector is mapped to a fixed-size prediction.
Sequence-processing architectures expand the range of problems that can be addressed.
One-to-many problems
A single input produces a sequence of outputs. For example, an image-captioning system receives one image and produces a sequence of words describing it.
image⟶“a dog runs through a field”Many-to-one problems
A sequence of inputs produces one output. For example, a video classifier receives a sequence of frames and predicts the action occurring in the video.
video frames⟶“playing tennis”Many-to-many or sequence-to-sequence problems
One sequence is converted into another sequence. Machine translation is a central example:
English sentence⟶Italian sentenceThe two sequences may have different lengths, and their words may appear in different orders. This makes translation a natural problem for sequence-processing architectures.
Sequence models are useful because they can handle inputs and outputs whose lengths and structures vary over time.
Think About It
Why would an image-classification network designed for one fixed-size input and one fixed-size output be poorly suited to translating an entire sentence?
2. Recurrent Neural Networks for Sequence-to-Sequence Problems
A recurrent neural network, or RNN, processes a sequence one element at a time while maintaining a hidden state that summarizes what has been processed so far.
At time step t, an RNN receives:
- The current input xt
- The previous hidden state ht−1
It then produces a new hidden state:
ht=f(xt,ht−1)The same recurrent unit and the same learned parameters are reused at every time step. This allows one network to process sequences of different lengths.
2.1 The encoder-decoder structure
A common method for sequence-to-sequence problems uses two RNNs:
- An encoder processes the input sequence.
- A decoder generates the output sequence.
For translation, the encoder processes the English sentence one word at a time. The final hidden state is treated as a summary of the entire input.
Suppose the input sequence contains four tokens:
x1,x2,x3,x4The encoder produces hidden states:
h1,h2,h3,h4The final encoder state, often h4, is used as a context vector c:
c=h4The context vector is intended to contain the information needed to generate the translated sentence.
The decoder then generates one output token at a time. Its recurrent unit uses:
- The previous output token yt−1
- The previous decoder hidden state st−1
- The context vector c
A simplified decoder update is:
st=g(yt−1,st−1,c)The new decoder state is then used to predict the next output token yt.
2.2 The fixed-vector bottleneck
This design creates a serious limitation. The entire input sequence must communicate with the decoder through one fixed-size vector c.
If c has dimension 1024, then it always has exactly 1024 numbers, regardless of whether the input is:
- A short sentence
- A paragraph
- A book
- A large collection of text
For a short sentence, a fixed vector may be sufficient. However, as the input becomes longer or more complicated, forcing all information into one vector creates a communication bottleneck.
The decoder may need to remember many details simultaneously:
- Which entities appeared
- The relationships among those entities
- The grammatical structure
- The order of events
- Important words that may be far apart
A single fixed-size summary may lose information before decoding even begins.
The RNN encoder-decoder bottleneck occurs because the entire input sequence is compressed into one fixed-length context vector.
Think About It
If a decoder is translating the final word of a very long paragraph, why might it be better for the decoder to access the original encoded words rather than rely only on one summary vector?
3. Attention: Removing the Bottleneck
The solution is to let the decoder look back at the entire encoded input whenever it needs to produce an output.
Instead of using one context vector for every decoder step, the model computes a new context vector at each step:
c1,c2,c3,…Each context vector is tailored to the particular output currently being generated.
For example, when generating an Italian word corresponding to “we see,” the decoder can assign high importance to the English words “we” and “see.” When generating a word corresponding to “sky,” it can focus on “sky.”
This mechanism is called attention because the model selectively focuses on different parts of the input.
4. Computing Attention Step by Step
Assume that the encoder produces hidden states:
h1,h2,…,hnAt decoder step t, the decoder has a hidden state st. The attention mechanism uses st to determine which encoder states are relevant.
4.1 Alignment scores
First, the model computes one scalar alignment score for each encoder state. The score measures how relevant hi is to the current decoder state st.
A general scoring function can be written as:
et,i=fatt(st,hi)Here, et,i is the score between decoder state st and encoder state hi.
One possible implementation concatenates the two vectors and passes them through a learned linear layer:
et,i=w⊤[sthi]+bThe exact function can vary, but it must produce one scalar for each pair.
4.2 Converting scores into attention weights
The raw alignment scores may be any real numbers, so they are passed through a softmax function:
αt,i=∑j=1nexp(et,j)exp(et,i)The resulting values satisfy:
0≤αt,i≤1and
i=1∑nαt,i=1Thus, the attention weights form a probability distribution over the input positions.
A large value of αt,i means that the model is assigning substantial importance to encoder state hi when producing the current output.
4.3 Constructing the context vector
The context vector is a weighted average, or more generally a weighted linear combination, of the encoder states:
ct=i=1∑nαt,ihiIf the model assigns high weights to the first and second encoder states, those states will contribute strongly to ct. If it assigns nearly zero weight to another state, that state will contribute very little.
The decoder then uses ct to produce its next hidden state and output token:
st+1=g(yt,st,ct)The important change is that the context vector is recomputed for every decoder step.
4.4 End-to-end learning
The model is not explicitly told which input word corresponds to which output word. Instead, the alignment scores, attention weights, and all other parameters are learned through the ordinary training objective.
For translation, the network receives many input-output sentence pairs and is trained to predict the correct output tokens. A cross-entropy loss measures the difference between the predicted and correct tokens.
Gradient descent adjusts:
- The encoder parameters
- The decoder parameters
- The attention scoring function
- Any projection matrices used by the model
Over time, the network learns which input regions are useful for predicting particular outputs.
This is important because manually labeling every alignment between every input word and output word would be expensive and difficult. Attention discovers useful alignments indirectly through the final task.
Attention is learned supervision-free with respect to alignment: the model learns where to look because doing so helps it predict the correct outputs.
5. Interpreting Attention Weights
Attention weights also provide a way to inspect what the network appears to be using.
Suppose a translation system is processing an English sentence and generating a French sentence. The attention weights can be arranged in a matrix:
- Each column corresponds to an input word.
- Each row corresponds to an output word.
- Each cell shows how strongly that output word attends to that input word.
A bright or high-valued cell indicates strong attention.
Alignment patterns
Several patterns can appear:
- A diagonal pattern suggests that input and output words correspond in approximately the same order.
- A reversed diagonal suggests that the languages use different word orders.
- A broader block suggests that several input words and several output words jointly contribute to one another.
- Concentrated attention on one position suggests a strong one-to-one correspondence.
Attention visualizations can therefore reveal that the network has learned useful structural relationships, including aspects of word order and grammatical organization.
However, attention weights should be interpreted carefully. They show where the model assigns weight during this computation, but they do not necessarily provide a complete explanation of every internal decision.
Think About It
What might a broad region of high attention indicate compared with a single sharply focused high-attention position?
6. Attention as an Independent Neural-Network Primitive
Attention was initially motivated as a way to improve RNN encoder-decoder systems. However, the computation is more general than the RNN context in which it first appeared.
The central operation is:
- Start with a query vector.
- Compare the query with a collection of data vectors.
- Convert the comparison scores into weights.
- Use those weights to summarize the data vectors.
The RNN interpretation is only one possible use:
- The encoder hidden states are the data vectors.
- The decoder hidden states are the query vectors.
- The attention output is the context vector.
The RNN itself is not essential to the attention computation.
6.1 Queries and data vectors
Suppose there is one query vector q and a collection of data vectors:
x1,x2,…,xnThe attention mechanism computes similarities between q and each xi, produces weights, and returns a weighted combination of the data:
y=i=1∑nαixiThis can be understood as a learned retrieval process. The query asks, “Which data vectors are relevant?” The attention weights determine the answer, and the output is a summary of the relevant information.
7. Scaled Dot-Product Attention
A general similarity function could be complicated. A particularly useful choice is the dot product.
For a query q and key ki, the similarity is:
q⊤kiA larger dot product generally indicates that the vectors point in more similar directions, assuming comparable magnitudes.
7.1 Why scaling is necessary
As vector dimension increases, dot products tend to grow in magnitude. Passing very large or very small scores into a softmax can make the softmax extremely concentrated.
For example, nearly all probability may be assigned to one position, while the remaining probabilities become almost zero. This can lead to very small gradients and make learning difficult.
To reduce this effect, the dot product is divided by the square root of the key dimension dk:
score(q,ki)=dkq⊤kiThis is called scaled dot-product attention.
The scaling helps maintain better numerical behavior and gradient flow as the vectors become higher-dimensional.
8. Matrix Form of Attention
Processing one query at a time would be inefficient. Neural-network hardware is especially effective at matrix multiplication, so attention is expressed in matrix form.
Let:
- Q be a matrix of query vectors.
- K be a matrix of key vectors.
- V be a matrix of value vectors.
The attention operation is:
Attention(Q,K,V)=softmax(dkQK⊤)V8.1 Similarity computation
The product
QK⊤computes every query-key dot product at once.
If there are nq queries and nk keys, the result is an nq×nk matrix. Each entry contains the similarity between one query and one key.
8.2 Softmax normalization
Softmax is applied separately across the keys for each query. Each query therefore receives its own probability distribution over the available keys.
The attention-weight matrix is:
A=softmax(dkQK⊤)Each row of A sums to 1.
8.3 Weighted value combinations
The final multiplication,
AVforms a weighted combination of the value vectors for every query. Thus, matrix multiplication performs both:
- The computation of similarities
- The computation of weighted summaries
This makes attention efficient to implement on GPUs and other parallel hardware.
9. Keys, Queries, and Values
A further generalization separates the roles played by the original data vectors.
Originally, the same vectors were used both:
- To compute similarity with the query
- To provide the information returned in the output
Attention instead projects each data vector into two distinct representations:
- A key representation used for matching.
- A value representation used for retrieval.
For an input data matrix X:
K=XWK V=XWVThe query matrix may come from another source:
Q=query inputsThe key and value projection matrices WK and WV are learned parameters.
The key and value dimensions need not theoretically be identical. The key dimension controls matching, while the value dimension controls the size of the information returned by the attention layer.
Search-engine analogy
A search engine illustrates the distinction:
- The user’s search text acts like a query.
- Stored representations used to match the search act like keys.
- The retrieved documents or answers act like values.
The text used to find a result does not have to be identical to the information returned as the result. Similarly, a neural network benefits from being able to match using one representation and retrieve using another.
10. Cross-Attention and Self-Attention
10.1 Cross-attention
Cross-attention uses two different sets of vectors:
- Queries from one source
- Keys and values from another source
For example, in machine translation:
- Decoder states provide the queries.
- Encoder states provide the keys and values.
In image captioning:
- Generated text states can provide queries.
- Image-region features can provide keys and values.
Cross-attention is useful whenever one type of object needs to retrieve information from another type of object.
10.2 Self-attention
Self-attention uses one set of input vectors to produce queries, keys, and values.
Given input vectors X:
Q=XWQ K=XWK V=XWVThe output is:
Y=softmax(dkQK⊤)VEach input vector can compare itself with every other input vector and gather information from the entire set.
Self-attention is useful when there is one collection of objects whose internal relationships need to be modeled. For example, the vectors may represent:
- Words in a sentence
- Patches in an image
- Elements of an audio sequence
- Objects or features in a structured input
Think About It
In an image-captioning system, why might cross-attention be more natural than self-attention at the point where the text generator needs to use visual information?
11. Permutation Equivariance
A basic self-attention layer has an important mathematical property: it is permutation equivariant.
Suppose the input vectors are shuffled. Because queries, keys, and values are computed independently from each input vector, the corresponding queries, keys, and values are shuffled in the same way.
The similarity matrix and attention weights are also rearranged consistently. As a result, the outputs are the same vectors as before, but shuffled in the same order as the inputs.
If a permutation is represented by P, then self-attention has the general behavior:
Attention(PX)=PAttention(X)This means the layer does not inherently care about the order in which the vectors are presented. It naturally operates on a set of vectors, even if those vectors are stored in a matrix.
Why this can be a problem
Order is essential in many data types.
For language, these two sequences contain the same words but have different meanings:
- “The dog chased the cat.”
- “The cat chased the dog.”
A plain self-attention layer cannot distinguish order unless order information is included in the inputs.
Positional embeddings
A common solution is to add or concatenate a positional embedding to each input vector. The positional information indicates where a vector occurs:
- Position 1
- Position 2
- Position 3
- And so on
The resulting vector contains both content information and location information.
With positional information, self-attention can model relationships such as:
- Which word came before another word
- How far apart two words are
- Which image patch lies above another patch
- Where an audio feature occurs in time
12. Masked Self-Attention
In ordinary self-attention, every input can attend to every other input. Some tasks require restricting these interactions.
12.1 Autoregressive language modeling
In language modeling, the model predicts a sequence one token at a time. When predicting the token at position t, it should be allowed to use only positions up to t.
Otherwise, the model could look at future tokens and simply copy the answer.
For example:
- The first output may use the first input token.
- The second output may use the first two input tokens.
- The third output may use the first three input tokens.
Future positions must be blocked.
12.2 Implementing the mask
After computing the raw attention scores, the model replaces forbidden entries with negative infinity:
et,i={et,i,−∞,if position i is allowedif position i is blockedAfter softmax:
softmax(−∞)=0Therefore, a blocked position receives zero attention weight and contributes nothing to the output.
Masked attention imposes a controlled interaction pattern without changing the rest of the attention mechanism.
13. Multi-Head Self-Attention
A single self-attention operation produces one particular pattern of relationships. A model may benefit from examining the input in several different ways at the same time.
Multi-head self-attention runs several independent attention mechanisms, called heads, in parallel.
For each head r:
Y(r)=Attention(XWQ(r),XWK(r),XWV(r))The head outputs are combined, commonly by concatenating them and applying an output projection:
Y=Concat(Y(1),Y(2),…,Y(H))WOEach head has the same general architecture but different learned weight matrices. Consequently, different heads can learn different relationships.
For language, one head might focus on:
- Nearby word relationships
- Subject-verb relationships
- Long-distance references
- Word-order patterns
The network is not explicitly told what each head should learn. The different patterns emerge through gradient-based training.
Efficient implementation
Although the conceptual description involves several separate attention operations, implementations can use batched matrix multiplications to compute the heads in parallel. The entire multi-head attention layer is therefore highly compatible with modern hardware.
14. Why Parallelization Matters
Parallelization means that many computations can occur simultaneously on different processors.
This matters because individual processors cannot necessarily become indefinitely faster. Modern large-scale computing instead gains power by coordinating many processors, such as those in GPUs or distributed clusters.
An algorithm is especially scalable when it allows many independent operations to be performed in parallel.
RNNs
RNNs are difficult to parallelize across sequence positions because:
ht=f(xt,ht−1)The computation of ht depends on ht−1, so position t cannot be computed until the previous position has been processed.
Convolutions
Convolutions are highly parallelizable because many spatial positions can be processed independently. However, convolution is fundamentally local. To connect distant parts of a large input, a network may need:
- Very large kernels
- Many stacked convolutional layers
Stacking many layers introduces additional sequential depth.
Self-attention
Self-attention allows every vector to interact with every other vector in one layer. Its main computations are matrix multiplications, which are highly parallelizable.
The main cost is that full attention for a sequence of length n requires approximately:
O(n2)pairwise interactions. The quadratic cost can become expensive for extremely long sequences. However, the additional computation also gives the model direct access to all pairwise relationships in the sequence.
Self-attention trades greater computational cost for direct, highly parallel access to global relationships.
15. The Transformer Architecture
A transformer is a neural-network architecture whose central computational primitive is self-attention.
A basic transformer block contains:
- Multi-head self-attention
- A residual connection
- Layer normalization
- A position-wise multilayer perceptron
- Another residual connection
- Another layer normalization
15.1 Self-attention sublayer
The input is a set or sequence of vectors X. Multi-head self-attention allows every vector to gather information from every other vector.
This is the communication stage: the vectors exchange information.
15.2 Residual connections
A residual connection adds the original input to the output of a sublayer:
Z=X+Sublayer(X)Residual connections help information and gradients flow through deep networks. They allow a layer to learn a useful modification to its input instead of having to reconstruct the entire representation from scratch.
15.3 Layer normalization
The result is passed through layer normalization, which stabilizes the numerical scale of activations and generally makes optimization more reliable.
Normalization is particularly useful in deep architectures because repeated transformations can otherwise cause activations to grow or shrink in undesirable ways.
15.4 Position-wise MLP or feed-forward network
Self-attention allows vectors to communicate with one another, but the architecture also needs a component that processes each vector individually.
A multilayer perceptron, often called a feed-forward network or FFN, is applied independently to every vector:
FFN(x)=W2σ(W1x+b1)+b2The same MLP parameters are used at every position, but each position is processed independently of the others in this sublayer.
The two main components therefore have complementary roles:
- Self-attention: lets representations interact.
- Position-wise MLP: transforms each representation independently.
15.5 Stacking transformer blocks
A transformer consists of multiple transformer blocks placed one after another. Each block refines the representations produced by the previous block.
The architecture has remained broadly similar while scaling from relatively small models to systems with many blocks and very large numbers of parameters.
Think About It
Why does a transformer need both self-attention and a position-wise MLP instead of using self-attention alone?
16. Transformers for Language
For language tasks, each word or token is converted into a vector representation. Positional information is included so that the model can distinguish different orders.
The resulting sequence of vectors is processed by transformer blocks. Depending on the task, the output can be used for:
- Predicting the next token
- Classifying an entire sequence
- Generating text
- Translating between languages
- Extracting information from text
For autoregressive generation, masked self-attention prevents a position from seeing future tokens. This ensures that the prediction at position t depends only on earlier information.
17. Transformers for Images
Transformers can also process images.
A typical procedure is:
- Divide the image into smaller patches.
- Convert each patch into a vector.
- Add positional information to the patch vectors.
- Process the patch vectors with transformer blocks.
- Use the resulting representations for the desired task.
For image classification, the output representations can be pooled into a single representation:
z=Pool(y1,y2,…,ym)A final linear layer can then produce class scores:
scores=Wz+bThe same general architecture can therefore process words, image patches, audio segments, or other collections of vectors.
18. Comparing the Main Sequence-Processing Primitives
Recurrent neural networks
RNNs:
- Process ordered one-dimensional sequences
- Maintain a hidden state over time
- Have inherently sequential computation
- Are difficult to parallelize across sequence positions
- Can suffer from fixed-vector bottlenecks in encoder-decoder designs
Convolution
Convolution:
- Operates naturally on grids
- Mixes information locally
- Is highly parallelizable
- Works well for images and other spatial data
- Needs large kernels or many layers to connect distant positions
Self-attention
Self-attention:
- Operates naturally on sets or sequences of vectors
- Allows every vector to interact with every other vector
- Is highly parallelizable through matrix multiplication
- Can model global relationships in one layer
- Has approximately quadratic computation and memory cost in sequence length
The architectural choice depends on the problem, but self-attention has become especially influential because it combines flexible global interaction with efficient parallel computation.
Comprehensive Review
Attention began as a solution to the fixed-length bottleneck in recurrent encoder-decoder networks. Rather than forcing an entire input sequence into one context vector, the decoder can create a new context vector at every output step.
The process works by comparing a query with data representations, converting the comparison scores into normalized attention weights, and using those weights to compute a weighted combination of the data. The query determines what information is relevant at the current moment.
The general attention mechanism uses:
- Queries to represent what the model is looking for
- Keys to represent how data can be matched
- Values to represent the information retrieved after matching
The standard computation is scaled dot-product attention:
Attention(Q,K,V)=softmax(dkQK⊤)VCross-attention compares two different sets of vectors, while self-attention creates queries, keys, and values from one set of inputs. Plain self-attention is permutation equivariant, so positional embeddings are needed when order matters. Masks can restrict which positions are allowed to interact, and multi-head attention lets the model learn several relationship patterns in parallel.
A transformer combines multi-head self-attention with residual connections, layer normalization, and position-wise multilayer perceptrons. Self-attention allows representations to communicate globally, while the MLP transforms each representation independently. Because the major operations are matrix multiplications, transformers are highly parallelizable and scalable, although full attention has quadratic cost in sequence length.
The central conceptual progression is therefore:
RNN sequence processing⟶attention for removing bottlenecks⟶standalone attention⟶self-attention⟶transformersTransformers are powerful because they provide a general mechanism for allowing many vector representations to exchange information directly while remaining compatible with large-scale parallel computation.

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