Self-Attention and Transformers
- 63Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What recurrent architecture was previously used to encode source sentences and generate target sequences in sequence-to-sequence NLP systems?
63 questions
- 1
What recurrent architecture was previously used to encode source sentences and generate target sequences in sequence-to-sequence NLP systems?
Model answer
A bidirectional LSTM was used to encode the source sentence, while a unidirectional LSTM generated the target sequence one step at a time.
Explanation
The bidirectional encoder supplied context from both directions, and the unidirectional decoder generated outputs sequentially.
- 2
Why was attention introduced for machine translation?
Model answer
Attention was introduced to avoid forcing the entire source sentence into a single fixed-size vector, which creates an information bottleneck.
Explanation
Attention gives the decoder flexible access to different parts of the encoded source sentence when producing each target word.
- 3
What is the linear interaction distance problem in recurrent neural networks?
Model answer
In an RNN, information between words that are far apart must pass through many sequential recurrent steps, making long-distance dependencies difficult to learn.
Explanation
The number of computational steps between two words grows with their distance in the sequence.
- 4
Use the sentence “The chef who bought the ingredients was praised” to explain why an RNN may struggle with long-distance dependencies.
Model answer
The relationship between “chef” and “was” must be transmitted through all intervening words and recurrent steps, so learning their grammatical dependency can be difficult.
Explanation
Although the words are related syntactically, they are separated by a long sequence in the left-to-right computation.
- 5
How do LSTMs improve on simple RNNs for long-distance dependencies, and what limitation remains?
Model answer
LSTMs model gradients across long distances better than simple RNNs, but they do not completely eliminate the difficulty of learning long-range dependencies.
Explanation
The gated structure reduces gradient problems, yet information still travels through a sequential chain of recurrent operations.
- 6
Why are recurrent neural networks difficult to parallelize on GPUs?
Model answer
The hidden state at time step t depends on the hidden state at time step t−1, so later states cannot be computed before earlier states.
Explanation
This sequential dependency creates roughly sequence-length-many unparallelizable operations in both the forward and backward passes.
- 7
How does the amount of sequential computation in an RNN change as sequence length increases?
Model answer
It grows linearly with sequence length because each additional position requires another dependent recurrent computation.
Explanation
A state near the end of the sequence must wait for all preceding states to be computed.
- 8
How does self-attention address the linear interaction distance problem?
Model answer
Self-attention allows any word to directly interact with any other word, regardless of their distance in the sequence.
Explanation
A word can attend directly to a distant word instead of receiving its information through many intermediate recurrent steps.
- 9
Why can self-attention be computed in parallel across sequence positions?
Model answer
Each word's attention representation can be computed from the entire set of word representations without waiting for another position's attention result.
Explanation
Unlike an RNN, self-attention does not require processing positions sequentially from left to right or right to left.
- 10
What is the key-value lookup interpretation of attention?
Model answer
A query is compared with a set of keys, and the corresponding values are combined according to the similarity between the query and each key.
Explanation
Attention acts like a soft lookup table rather than an exact dictionary lookup.
- 11
How does attention differ from an exact lookup-table operation?
Model answer
An exact lookup selects the value associated with a matching key, whereas attention softly compares the query with all keys and computes a weighted combination of their values.
Explanation
The weights are typically produced by applying softmax to similarity scores.
- 12
What roles do queries, keys, and values play in self-attention?
Model answer
A query represents what a word is seeking, keys represent what each word offers for matching, and values contain the information that is combined into the output.
Explanation
Each input word is transformed into a query, key, and value vector using separate learned parameter matrices.
- 13
How are query, key, and value vectors produced from word embeddings?
Model answer
Each non-contextual word embedding is multiplied by a separate learned matrix to produce its query, key, and value vectors.
Explanation
The embedding initially depends only on word identity; self-attention uses these transformations to create context-dependent representations.
- 14
How is the similarity between word i and word j computed in basic self-attention?
Model answer
The similarity score is the dot product between the query vector for word i and the key vector for word j.
Explanation
A larger dot product indicates that the query and key are more aligned in the learned representation space.
- 15
How are raw self-attention scores converted into attention weights?
Model answer
The scores for a query are passed through a softmax over all possible key positions, producing nonnegative weights that sum to one.
Explanation
Softmax converts relative similarities into a distribution over the words being attended to.
- 16
How is the output representation for a word computed in self-attention?
Model answer
The output is a weighted sum of all value vectors, where each value is weighted by the attention between the word's query and the corresponding key.
Explanation
This weighted sum incorporates information from the entire sequence into the word's representation.
- 17
Why can a word attend to itself in self-attention, and is this behavior fixed?
Model answer
Self-attention includes the word's own key among the possible keys, but learned query and key transformations determine whether the word gives itself substantial attention.
Explanation
The model can learn either to emphasize or to suppress self-attention depending on the task and data.
- 18
What does sequence-stacked self-attention mean?
Model answer
Instead of processing words one at a time, all word embeddings are stacked into a matrix and transformed using matrix multiplication.
Explanation
This vectorized representation lets GPUs compute the transformations for all sequence positions efficiently.
- 19
How does the matrix product between queries and transposed keys compute all pairwise attention scores?
Model answer
Multiplying the query matrix by the transposed key matrix produces a matrix whose entry at row i, column j is the dot product between query i and key j.
Explanation
One matrix multiplication therefore computes every query-key similarity in the sequence at once.
- 20
Why does basic self-attention need positional representations?
Model answer
Self-attention by itself is insensitive to the order of its input vectors, so it would produce the same representations for sequences containing the same words in different orders.
Explanation
For example, “Zuko made his uncle” and “his uncle made Zuko” contain the same word vectors but have different meanings because their order differs.
- 21
How are positional representations incorporated into word embeddings?
Model answer
A position vector is added to the word embedding at each sequence index before the self-attention computation.
Explanation
The resulting input represents both the word identity and its location in the sequence.
- 22
Why can positional information usually be added only at the input to a Transformer?
Model answer
Once position information is included in the initial representations, later layers can propagate and use it without adding a new position vector at every layer.
Explanation
The network receives positional information at the start and transforms it along with the word representations.
- 23
How do sinusoidal positional representations encode position?
Model answer
They represent each position with a vector whose dimensions contain sine or cosine functions evaluated at different periods.
Explanation
Different dimensions vary at different frequencies, allowing the collection of values to distinguish many position indices.
- 24
What is one motivation for using multiple sinusoidal periods in positional encodings?
Model answer
Different periods provide patterns at different scales, which can help represent position and potentially support generalization to longer sequences.
Explanation
The original intuition was that relative periodic patterns might be more useful than relying only on an absolute position index, although extrapolation does not work reliably in practice.
- 25
How do learned positional embeddings differ from sinusoidal positional representations?
Model answer
Learned positional embeddings are parameters that the model directly learns for each position up to a specified maximum sequence length.
Explanation
They are flexible and data-driven, but positions beyond the learned maximum cannot be handled directly.
- 26
What is the main limitation of learned positional embeddings with respect to sequence length?
Model answer
A model with learned embeddings for a maximum length N cannot directly represent sequences longer than N.
Explanation
The model has no learned position vector for an index beyond its configured maximum.
- 27
Why is extending Transformer context length computationally expensive?
Model answer
Self-attention computes interactions between every pair of positions, so the memory and computation associated with these interactions grow quadratically with sequence length.
Explanation
The attention-score matrix has dimensions corresponding to the sequence length in both axes.
- 28
What problem results from applying self-attention repeatedly without nonlinear feed-forward layers?
Model answer
Repeated self-attention mainly re-averages value vectors, so stacking it does not provide the nonlinear expressive power normally associated with deep networks.
Explanation
Without nonlinear transformations, multiple attention operations can collapse into an operation resembling one larger weighted averaging process.
- 29
What is the purpose of the position-wise feed-forward network in a Transformer?
Model answer
It nonlinearly processes each output vector from self-attention, adding expressive deep-learning transformations after contextual information has been incorporated.
Explanation
The same type of feed-forward network is applied independently to each sequence position.
- 30
How does a position-wise feed-forward network differ from self-attention?
Model answer
Self-attention combines information across sequence positions, whereas the position-wise feed-forward network processes each position independently.
Explanation
The two components complement each other by combining contextual mixing with local nonlinear processing.
- 31
Why is the feed-forward portion of a Transformer computationally efficient on GPUs?
Model answer
Each position can be processed independently, allowing the computations to be performed in parallel.
Explanation
The feed-forward network does not introduce dependencies between different sequence positions.
- 32
Why is future masking needed when predicting a sequence autoregressively?
Model answer
Future masking prevents the representation at position i from using words at positions greater than i, which would reveal the answer during training.
Explanation
A language model must predict the next word using only the current and preceding context.
- 33
How is future masking implemented in self-attention?
Model answer
Attention scores involving future positions are set to negative infinity before softmax, causing their attention weights to become zero.
Explanation
The model can then compute the full score matrix in parallel while ensuring that future information contributes nothing.
- 34
Why can masking preserve parallel computation even though it enforces a left-to-right information constraint?
Model answer
The model computes all pairwise scores simultaneously and then masks the forbidden future entries instead of computing each position sequentially.
Explanation
Masking restricts information flow without recreating the sequential dependency of an RNN.
- 35
Why is future masking normally omitted from a Transformer encoder?
Model answer
An encoder generally needs bidirectional context, so each input position should be allowed to attend to both earlier and later positions.
Explanation
The source sentence is available in full, unlike an autoregressive decoder output that must not see future target words.
- 36
What is the minimal self-attention building block described in the lecture?
Model answer
It consists of word embeddings combined with position representations, self-attention, a position-wise feed-forward network, and optional future masking when required.
Explanation
These components address missing order information, missing nonlinearities, and forbidden access to future tokens.
- 37
What is multi-head self-attention?
Model answer
Multi-head self-attention performs several independent self-attention operations with separate query, key, and value projections, then combines their outputs.
Explanation
Each head can learn to focus on different relationships or information in the sequence.
- 38
Why can multiple attention heads be useful compared with a single attention operation?
Model answer
Different heads can attend to different parts of a sequence for different reasons, such as identifying syntactic relationships or relevant entities.
Explanation
A single weighted average may be insufficient to represent several distinct types of relationships simultaneously.
- 39
How are the dimensions of each attention head related to the model dimension?
Model answer
If the model dimension is D and there are H heads, each head typically operates in a lower-dimensional space of roughly D/H dimensions.
Explanation
Reducing the dimensionality per head keeps the total computation manageable while allowing several attention patterns.
- 40
How is the output of multi-head attention formed?
Model answer
The outputs of all heads are concatenated and passed through a final learned linear transformation.
Explanation
Concatenation preserves the information from each head, while the final projection mixes it into the model dimension.
- 41
Are attention heads guaranteed to learn completely different functions?
Model answer
No. Models are not explicitly forced to make heads different, although they often develop partially specialized roles and may contain some redundancy.
Explanation
Specialization emerges from training rather than from a strict constraint imposed by the architecture.
- 42
Why is multi-head attention efficient to implement using tensor reshaping?
Model answer
The projected sequence representations can be reshaped so that the head dimension behaves like a batch dimension, allowing the attention operations for all heads to run together.
Explanation
Reshaping and transposing tensors enable efficient parallel matrix operations without looping over heads.
- 43
What is scaled dot-product attention, and why is it used?
Model answer
Scaled dot-product attention divides each query-key dot product by the square root of the head dimension before softmax.
Explanation
Without scaling, dot products tend to become large in high dimensions, making softmax overly sharp and producing very small gradients.
- 44
What is the purpose of a residual connection in a Transformer block?
Model answer
A residual connection adds a layer's input to its output, allowing the layer to learn a residual change rather than the entire transformation.
Explanation
The direct path also gives gradients an easier route through the network and can make optimization more stable.
- 45
How can residual connections help with vanishing gradients?
Model answer
The identity path in a residual connection allows gradients to pass directly backward without being repeatedly transformed by the intervening layer.
Explanation
This direct route can preserve gradient information even when the learned transformation has weak or shrinking gradients.
- 46
Why might residual connections provide a useful initialization for deep networks?
Model answer
If the learned transformation initially contributes little, the residual block behaves approximately like the identity function.
Explanation
Starting near the identity can make it easier for information and gradients to flow through many stacked layers.
- 47
What does layer normalization normalize in a Transformer?
Model answer
For an individual word representation, layer normalization normalizes the values across its model dimensions to have approximately zero mean and unit standard deviation.
Explanation
It reduces uninformative variation in the scale of representations passed between layers.
- 48
How are the mean and standard deviation for layer normalization computed?
Model answer
They are computed across the dimensions of one word vector rather than across different sequence positions or different examples in a batch.
Explanation
Each representation is normalized independently, so its statistics do not depend on other words or batch elements.
- 49
Why is a small epsilon added in the denominator of layer normalization?
Model answer
A small epsilon prevents division by zero or unstable division when the variance is very small.
Explanation
It ensures numerical stability during normalization.
- 50
What optional learned parameters can follow the standardization step in layer normalization?
Model answer
Learned scale and shift parameters can rescale and offset the normalized representation.
Explanation
These parameters allow the model to restore useful variation after normalization if needed.
- 51
What operations make up one standard Transformer block?
Model answer
A block applies self-attention, an add-and-normalize operation, a position-wise feed-forward network, and another add-and-normalize operation.
Explanation
The add-and-normalize operations combine residual connections with layer normalization.
- 52
How is a Transformer decoder different from a Transformer encoder?
Model answer
A decoder uses masked self-attention to prevent access to future positions, whereas an encoder uses unmasked self-attention to provide bidirectional context.
Explanation
The decoder generates outputs autoregressively, while the encoder processes an input sequence whose full context is available.
- 53
What is cross-attention in an encoder-decoder Transformer?
Model answer
Cross-attention uses decoder representations as queries and encoder outputs as keys and values.
Explanation
Each decoder position can therefore retrieve relevant information from the entire encoded source sequence.
- 54
Why does an encoder-decoder Transformer use both masked self-attention and cross-attention in its decoder?
Model answer
Masked self-attention lets the decoder use previously generated target words without seeing future ones, while cross-attention lets it access the encoded source sentence.
Explanation
Together, these operations support autoregressive generation conditioned on the input sequence.
- 55
In machine translation, what information can the encoder and decoder attend to?
Model answer
The encoder can attend to all source words, while the decoder attends to previous target words through masking and to all encoder outputs through cross-attention.
Explanation
This separates full source understanding from causally constrained target generation.
- 56
Why did Transformers become more efficient to train than recurrent sequence models?
Model answer
Transformers remove recurrent time-step dependencies, allowing more operations to run in parallel and making better use of GPUs and large amounts of data.
Explanation
Their parallel computation substantially reduces the training bottleneck caused by sequential RNN states.
- 57
What impact did Transformers have on modern NLP applications?
Model answer
They achieved strong results across tasks such as machine translation and document generation and became the dominant foundation for many modern NLP systems.
Explanation
Their combination of parallelism, scalability, and effective context modeling enabled major advances beyond LSTM-based systems.
- 58
How did Transformer efficiency contribute to the rise of pre-training?
Model answer
Efficient parallel computation made it practical to train models on very large datasets with substantial computational resources, supporting the development of pre-trained language models.
Explanation
Large-scale pre-training benefited directly from the ability to process many tokens efficiently.
- 59
What is the main computational limitation of standard self-attention for long sequences?
Model answer
Its all-pairs interaction pattern requires computation and memory that grow quadratically with sequence length.
Explanation
Very long inputs, such as entire novels or large documents, can therefore become impractical to process.
- 60
Why is the quadratic attention problem especially relevant for document-level processing?
Model answer
As the number of tokens in a document increases, the number of pairwise interactions increases much faster, making memory and computation requirements quickly become infeasible.
Explanation
A sequence of length N produces an attention-score matrix with approximately N2 entries.
- 61
How does the sequence-length complexity of standard RNNs compare with that of self-attention?
Model answer
RNN computation grows roughly linearly with sequence length, whereas the pairwise interaction computation of standard self-attention grows quadratically.
Explanation
RNNs have fewer pairwise interactions but suffer from sequential processing and long-distance dependency problems.
- 62
What are researchers trying to improve besides the quadratic cost of self-attention?
Model answer
They have explored more effective positional representations and other architectural modifications to improve the Transformer.
Explanation
Absolute position embeddings are not always the ideal way to represent relationships between positions, especially in long contexts.
- 63
Why might reducing the number of attention operations not always produce a large practical speedup in very large models?
Model answer
In large models, much of the total computation may occur in the feed-forward networks rather than in self-attention.
Explanation
Consequently, optimizing quadratic attention alone may not remove the dominant computational cost.

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