Self-Attention and Transformers
- 50Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is the main limitation of an RNN's linear interaction distance?
What is the main limitation of an RNN's linear interaction distance?
50 questions
- 1
What is the main limitation of an RNN's linear interaction distance?
- A
Words at adjacent positions cannot influence one another during computation
- B
The model cannot represent any dependency involving more than two words
- C
The model always treats every word as independent of its sentence context
- D
Words separated by many time steps may be difficult to connect through computation
Correct answer
DWords separated by many time steps may be difficult to connect through computation
Explanation
In an RNN, information must pass through each intermediate time step. Consequently, words that are far apart may have difficulty interacting and learning long-distance dependencies.
- A
- 2
Why can an RNN struggle to learn that "chef" and "was" are related in a long sentence?
- A
The gradient must propagate through many recurrent steps between the two words
- B
The words must have identical embeddings before the RNN can relate them
- C
The recurrent matrix removes all information about earlier words
- D
The RNN can only process nouns and verbs at separate time steps
Correct answer
AThe gradient must propagate through many recurrent steps between the two words
Explanation
The relationship between distant words must be learned through repeated applications of the recurrent transformation, which can make gradient propagation difficult.
- A
- 3
What does the dependence on sequence index imply for an RNN's computation?
- A
The model can process future positions before processing earlier positions
- B
Every hidden state can be computed independently from the input sequence
- C
The hidden state at one position depends on hidden states computed earlier
- D
The number of recurrent operations decreases as sequence length increases
Correct answer
CThe hidden state at one position depends on hidden states computed earlier
Explanation
An RNN must compute earlier hidden states before later hidden states, creating a sequential dependency on the position or time index.
- A
- 4
Why are RNN operations difficult to parallelize on a GPU?
- A
GPU matrix multiplication cannot be used with recurrent weight matrices
- B
RNNs perform no matrix multiplications during their forward passes
- C
The hidden state at time step t requires the hidden state from an earlier step
- D
Each word must be converted into a different vocabulary before processing
Correct answer
CThe hidden state at time step t requires the hidden state from an earlier step
Explanation
The hidden state at time step t cannot be computed until preceding hidden states have been computed, producing approximately sequence-length many unparallelizable operations.
- A
- 5
How do LSTMs improve on simple RNNs without fully solving the long-distance problem?
- A
They guarantee perfect learning of every dependency in a long document
- B
They model gradients across long distances better, but their sequential structure remains
- C
They replace every word representation with a fixed one-hot vector
- D
They eliminate all sequential dependencies while retaining recurrent computation
Correct answer
BThey model gradients across long distances better, but their sequential structure remains
Explanation
LSTMs handle gradient propagation across long distances better than simple RNNs, but they still process sequences recurrently and do not completely eliminate long-distance difficulties.
- A
- 6
What does attention provide in a sequence-to-sequence model?
- A
A replacement for word embeddings with exact dictionary lookups
- B
A guarantee that the decoder generates all target words simultaneously
- C
Flexible access to encoder information instead of one fixed sentence vector
- D
A way to remove the need for an encoder entirely
Correct answer
CFlexible access to encoder information instead of one fixed sentence vector
Explanation
Attention lets a decoder selectively access information from the encoder, avoiding the bottleneck of compressing an entire source sentence into one vector.
- A
- 7
What is the key-value lookup interpretation of attention?
- A
Keys and values are averaged before any query is introduced
- B
Each value selects a query and replaces the corresponding key
- C
A query exactly matches one key and discards all other values
- D
A query softly matches keys and uses the resulting weights to combine values
Correct answer
DA query softly matches keys and uses the resulting weights to combine values
Explanation
Attention performs a fuzzy lookup: the query is compared with every key, the similarities are normalized into weights, and the values are combined using those weights.
- A
- 8
How does attention differ from an exact dictionary lookup?
- A
Attention returns a key instead of the value associated with that key
- B
Attention cannot compare a query with more than one key
- C
Attention requires every query to be identical to a stored key
- D
Attention usually assigns soft weights to multiple keys rather than selecting one exact key
Correct answer
DAttention usually assigns soft weights to multiple keys rather than selecting one exact key
Explanation
A dictionary performs an exact match, whereas attention computes similarities between a query and all keys and typically distributes weight across several values.
- A
- 9
What role does the softmax function play in attention?
- A
It transforms each value vector into a new key vector
- B
It removes the query from the attention computation
- C
It ensures that all keys receive exactly the same weight
- D
It converts similarity scores into normalized attention weights
Correct answer
DIt converts similarity scores into normalized attention weights
Explanation
Softmax converts the raw query-key similarity scores into normalized weights that can be used in a weighted sum of the values.
- A
- 10
How is the output of attention computed after obtaining attention weights?
- A
By selecting the value with the smallest similarity score
- B
By taking a weighted sum of the value vectors
- C
By averaging the query with the vocabulary embeddings
- D
By concatenating all keys without using the values
Correct answer
BBy taking a weighted sum of the value vectors
Explanation
The attention output is the sum of the value vectors, with each value multiplied by its query-key attention weight.
- A
- 11
Why can self-attention address long-distance interactions more directly than an RNN?
- A
Self-attention stores the entire sequence in one recurrent hidden state
- B
Self-attention processes only neighboring words and ignores distant ones
- C
Self-attention requires one computation for every intermediate word
- D
Any word can potentially attend directly to any other word in the sequence
Correct answer
DAny word can potentially attend directly to any other word in the sequence
Explanation
Self-attention computes interactions between all pairs of positions, so distant words do not need to communicate through every intervening position.
- A
- 12
What is the purpose of the embedding matrix in the described self-attention model?
- A
It maps contextual vectors back into sequence positions
- B
It prevents different words from receiving different representations
- C
It computes the softmax weights between every pair of words
- D
It maps vocabulary identities to non-contextual vectors of dimension D
Correct answer
DIt maps vocabulary identities to non-contextual vectors of dimension D
Explanation
The embedding matrix maps each vocabulary item to a vector in 4\mathord{}D dimensions. These initial word embeddings depend on word identity but not on context.
- A
- 13
What are the query, key, and value vectors in self-attention derived from?
- A
Different learned linear transformations of each word's embedding
- B
The attention weights after the softmax operation
- C
Three copies of the original vocabulary index with no learned parameters
- D
Only the words appearing before the current word
Correct answer
ADifferent learned linear transformations of each word's embedding
Explanation
For each input embedding xi, separate learned matrices Q, K, and V produce its query, key, and value vectors.
- A
- 14
What does the score eij=qi⊤kj represent?
- A
The number of recurrent steps between positions i and j
- B
The probability that position i is the next vocabulary item
- C
The similarity between the query for position i and the key for position j
- D
The distance between the values at positions i and j
Correct answer
CThe similarity between the query for position i and the key for position j
Explanation
The dot product qi⊤kj measures how strongly the query at position i matches the key at position j.
- A
- 15
For a fixed query position i, how is the attention weight assigned to position j obtained?
- A
By applying softmax to eij across all possible key positions
- B
By dividing eij by the value vector at position j
- C
By applying softmax independently to each coordinate of vj
- D
By selecting j whenever eij is negative
Correct answer
ABy applying softmax to eij across all possible key positions
Explanation
The weight αij is the softmax-normalized score for position j among all keys considered by query i.
- A
- 16
What is the self-attention output oi for position i?
- A
oi=∑jαijvj
- B
oi=qi⊤ki
- C
oi=∑jeijqj
- D
oi=softmax(vi)
Correct answer
Aoi=∑jαijvj
Explanation
The output at position i is the weighted sum of all value vectors, using the attention weights αij.
- A
- 17
Why are separate Q and K matrices useful in self-attention?
- A
They remove the need to compute value vectors
- B
They force every word to attend to itself with maximum weight
- C
They allow the model to learn how queries and keys should be compared
- D
They ensure that attention is symmetric between every pair of words
Correct answer
CThey allow the model to learn how queries and keys should be compared
Explanation
Separate learned transformations allow the model to determine which aspects of a representation should serve as queries and which should serve as keys. A word need not automatically attend strongly to itself.
- A
- 18
What major information is missing from basic self-attention when no positional representation is added?
- A
The dimensionality of each value vector
- B
The ability to compute a weighted average
- C
The order in which words occur in the sequence
- D
The identity of every word in the vocabulary
Correct answer
CThe order in which words occur in the sequence
Explanation
Basic self-attention operates on a set of vectors and does not directly encode their sequence indices. Therefore, different word orders can produce the same representations.
- A
- 19
Why would basic self-attention treat "Zuko made his uncle" and "his uncle made Zuko" identically?
- A
The value matrix removes all syntactic information from words
- B
The model can process only sentences with repeated words
- C
The softmax function always produces uniform attention weights
- D
The word embeddings do not indicate the positions at which the words occur
Correct answer
DThe word embeddings do not indicate the positions at which the words occur
Explanation
Without positional information, self-attention sees the same collection of word vectors regardless of their order, even though the two sentences have different meanings.
- A
- 20
How can positional vectors be incorporated into the input of a self-attention network?
- A
By adding a position vector to the word embedding at each index
- B
By replacing every word embedding with its sequence index
- C
By applying softmax directly to the position indices
- D
By masking every word that does not occur at position one
Correct answer
ABy adding a position vector to the word embedding at each index
Explanation
A positional vector pi can be added to the word embedding xi, allowing the resulting representation to encode both word identity and position.
- A
- 21
How do sinusoidal positional representations encode position?
- A
They assign a separate one-hot vector to every possible sentence
- B
They apply sine or cosine functions with different periods across dimensions
- C
They use the same constant vector for every sequence position
- D
They randomly permute the dimensions of each word embedding
Correct answer
BThey apply sine or cosine functions with different periods across dimensions
Explanation
Sinusoidal representations use sine and cosine functions whose periods vary across dimensions, producing position-dependent vectors.
- A
- 22
What is a limitation of learned absolute positional embeddings?
- A
They prevent word embeddings from containing lexical information
- B
A model trained with a maximum length n has no learned position vectors beyond n
- C
They cannot represent any position within the training length
- D
They require recurrent computation across all sequence positions
Correct answer
BA model trained with a maximum length n has no learned position vectors beyond n
Explanation
If the model learns a position matrix for only n positions, it cannot directly represent a sequence position beyond n without some additional method.
- A
- 23
Why is sequence length a practical problem for self-attention?
- A
The embedding matrix grows exponentially with sequence length
- B
The model can attend to only one word for each sequence
- C
Self-attention requires exactly n recurrent hidden states
- D
The all-pairs interaction matrix has dimensions n×n
Correct answer
DThe all-pairs interaction matrix has dimensions n×n
Explanation
Self-attention computes scores for every pair of positions, producing an n×n matrix and therefore quadratic memory and computation with respect to sequence length.
- A
- 24
Why is a feed-forward network added after self-attention?
- A
It introduces nonlinear processing of each attention output vector
- B
It supplies the missing query-key similarity scores
- C
It removes the contextual information created by attention
- D
It forces the network to process words sequentially
Correct answer
AIt introduces nonlinear processing of each attention output vector
Explanation
Self-attention by itself mainly computes weighted averages. A position-wise feed-forward network adds nonlinear transformations and greater expressive power.
- A
- 25
How is the feed-forward network applied within a Transformer block?
- A
Each position's attention output is processed independently by the same network
- B
All positions are concatenated into one vector before one recurrent operation
- C
Each position uses a completely unrelated feed-forward network
- D
Only the first position is passed through the feed-forward network
Correct answer
AEach position's attention output is processed independently by the same network
Explanation
The feed-forward layer is position-wise: every output vector is processed independently, typically using shared parameters across positions.
- A
- 26
What problem does causal masking solve?
- A
It prevents a position from using information from future positions
- B
It prevents every position from attending to its own representation
- C
It removes all attention interactions between different sentences
- D
It makes the encoder unable to access the source sentence
Correct answer
AIt prevents a position from using information from future positions
Explanation
For autoregressive generation, the representation used to predict a word must not access later words. Causal masking blocks those future positions.
- A
- 27
How is causal masking implemented before softmax?
- A
Past-position scores are replaced with zero before normalization
- B
Future-position scores are replaced with negative infinity or an equivalent value
- C
The query vector is removed whenever a future word exists
- D
Future-position values are multiplied by a large positive constant
Correct answer
BFuture-position scores are replaced with negative infinity or an equivalent value
Explanation
Setting future scores to negative infinity makes their softmax weights effectively zero, so the current position cannot attend to them.
- A
- 28
Why can causal masking still permit efficient training?
- A
The model avoids calculating any attention scores involving earlier words
- B
Masking removes the need for matrix multiplication
- C
The decoder computes each position with a separate recurrent loop
- D
All pairwise scores can be computed together and future scores can then be masked
Correct answer
DAll pairwise scores can be computed together and future scores can then be masked
Explanation
The complete score matrix can be computed in parallel, after which entries corresponding to future positions are masked before softmax.
- A
- 29
Where is masking generally used in a standard encoder-decoder Transformer?
- A
In both encoder and decoder self-attention in exactly the same way
- B
In encoder self-attention, but not in decoder self-attention
- C
In neither encoder nor decoder attention
- D
In decoder self-attention, but not in encoder self-attention
Correct answer
DIn decoder self-attention, but not in encoder self-attention
Explanation
The encoder needs bidirectional access to the source sentence, whereas the autoregressive decoder must be prevented from looking at future target tokens.
- A
- 30
What is the main purpose of multi-head self-attention?
- A
To restrict each word to attending to only one other word
- B
To make every head use exactly the same query, key, and value matrices
- C
To eliminate the need for a final transformation after attention
- D
To let different attention mechanisms focus on different relationships or information
Correct answer
DTo let different attention mechanisms focus on different relationships or information
Explanation
Different heads have separate learned projections, allowing them to attend to different parts of a sequence for different reasons, such as syntactic or semantic relationships.
- A
- 31
How are the parameters of different attention heads related?
- A
The heads are fixed copies with no independently learned parameters
- B
All heads share one projection matrix but use different softmax functions
- C
Each head has its own query, key, and value projection matrices
- D
Each head uses only the value matrix and omits queries and keys
Correct answer
CEach head has its own query, key, and value projection matrices
Explanation
Multi-head attention defines independent Q, K, and V matrices for each head, allowing the heads to specialize.
- A
- 32
Why are the query, key, and value vectors in each head projected to a lower dimension?
- A
To ensure that all heads produce identical attention distributions
- B
To prevent the model from computing any pairwise similarities
- C
To encode sequence position without any positional vectors
- D
To make multiple heads computationally manageable while preserving separate subspaces
Correct answer
DTo make multiple heads computationally manageable while preserving separate subspaces
Explanation
Each head typically works in a space of dimension D/H, making it possible to use several heads without multiplying the full cost by the number of heads.
- A
- 33
What happens after the outputs of the attention heads are computed?
- A
They are discarded except for the head with the largest score
- B
They are fed sequentially into a recurrent network
- C
They are concatenated and passed through a final linear transformation
- D
They are averaged before any value vectors are used
Correct answer
CThey are concatenated and passed through a final linear transformation
Explanation
Each head produces an output in a lower-dimensional space. These outputs are concatenated and then mixed using a final learned linear transformation.
- A
- 34
How does sequence stacking improve the implementation of self-attention?
- A
It represents all word embeddings as one matrix and uses large matrix multiplications
- B
It requires the sequence to be processed from left to right
- C
It processes each word in a separate Python loop to reduce memory use
- D
It replaces all word embeddings with one scalar sentence representation
Correct answer
AIt represents all word embeddings as one matrix and uses large matrix multiplications
Explanation
Stacking the n word embeddings creates an n×D matrix, allowing the projections and attention computations to be vectorized efficiently on GPUs.
- A
- 35
What does the matrix product XQ(XK)⊤ compute?
- A
The matrix of all query-key dot-product scores
- B
The output of the feed-forward network at each position
- C
The weighted sum of all value vectors after softmax
- D
The positional embedding for every sequence index
Correct answer
AThe matrix of all query-key dot-product scores
Explanation
The product forms an n×n matrix whose entry at row i and column j is the dot product between query qi and key kj.
- A
- 36
What is the purpose of scaled dot-product attention?
- A
It replaces all query and key projections with identity matrices
- B
It guarantees that every attention weight is exactly uniform
- C
It keeps large-dimensional dot products from making softmax gradients too small
- D
It increases the sequence length that can be represented by learned positions
Correct answer
CIt keeps large-dimensional dot products from making softmax gradients too small
Explanation
As dimensionality grows, dot products can become large. Dividing by a scale related to the head dimension keeps softmax inputs better behaved and helps gradients.
- A
- 37
What does a residual connection add to a layer's output?
- A
The input to the layer is added to the transformation produced by the layer
- B
The output of the layer is replaced by the previous layer's input
- C
The attention scores are added to the vocabulary logits
- D
The position vector is added only after the final prediction
Correct answer
AThe input to the layer is added to the transformation produced by the layer
Explanation
A residual connection produces an output such as x+f(x), allowing the layer to learn a residual modification while providing a direct path for information and gradients.
- A
- 38
Why do residual connections help optimization?
- A
They provide an identity path through which gradients can pass directly
- B
They eliminate all nonlinearities from the network
- C
They prevent the model from using information from earlier layers
- D
They force every layer to learn a completely new representation
Correct answer
AThey provide an identity path through which gradients can pass directly
Explanation
The identity path has derivative one, which can help gradients avoid vanishing through the transformed layer. Residual connections can also make a layer initially behave approximately like the identity.
- A
- 39
What does layer normalization normalize in the described Transformer?
- A
All words in a document using one shared document mean
- B
All examples in a batch using one shared batch mean
- C
Only the attention weights associated with one query
- D
The coordinates within each individual word vector
Correct answer
DThe coordinates within each individual word vector
Explanation
Layer normalization computes statistics across the dimensions of one vector, normalizing that vector independently rather than sharing statistics across sequence positions or batch examples.
- A
- 40
What transformation is central to layer normalization?
- A
Multiply every coordinate by its sequence index and apply softmax
- B
Subtract the batch mean and divide by the batch size
- C
Subtract the vector mean and divide by its standard deviation plus a small epsilon
- D
Replace every coordinate with the largest coordinate in the vector
Correct answer
CSubtract the vector mean and divide by its standard deviation plus a small epsilon
Explanation
For a vector x, layer normalization uses a form of (x−μ)/σ2+ϵ, optionally followed by learned scale and shift parameters.
- A
- 41
Why is a small epsilon included in layer normalization?
- A
To force the normalized mean to become positive
- B
To increase the number of dimensions in each word vector
- C
To prevent numerical instability when the variance is very small
- D
To ensure that all positions receive nonzero attention
Correct answer
CTo prevent numerical instability when the variance is very small
Explanation
The epsilon term keeps the denominator from becoming zero or extremely small when the vector has little variation.
- A
- 42
What is the structure of a typical Transformer block described in the lecture?
- A
Attention followed by add-and-normalize, then feed-forward followed by add-and-normalize
- B
A single linear transformation followed by vocabulary lookup
- C
Feed-forward computation followed by recurrence and then positional masking
- D
Two recurrent layers followed by one unmasked attention operation
Correct answer
AAttention followed by add-and-normalize, then feed-forward followed by add-and-normalize
Explanation
A Transformer block applies self-attention, a residual connection and layer normalization, then a position-wise feed-forward network followed by another residual connection and layer normalization.
- A
- 43
What distinguishes a Transformer encoder from a causal Transformer decoder?
- A
The encoder uses unmasked self-attention, whereas the decoder uses masked self-attention
- B
The encoder uses only values, whereas the decoder uses only queries
- C
The encoder has no feed-forward layers, whereas the decoder has several
- D
The encoder processes one word at a time, whereas the decoder is fully parallel
Correct answer
AThe encoder uses unmasked self-attention, whereas the decoder uses masked self-attention
Explanation
An encoder builds bidirectional contextual representations, so its self-attention is unmasked. A causal decoder must mask future positions during autoregressive prediction.
- A
- 44
What is the purpose of cross-attention in an encoder-decoder Transformer?
- A
It combines the encoder and decoder vocabularies before embedding
- B
It replaces masked decoder self-attention with a recurrent layer
- C
It lets the encoder attend only to future decoder positions
- D
It lets decoder positions query representations produced by the encoder
Correct answer
DIt lets decoder positions query representations produced by the encoder
Explanation
In cross-attention, decoder representations supply the queries, while encoder outputs supply the keys and values. This lets each decoder position access the encoded source sentence.
- A
- 45
In encoder-decoder cross-attention, where do the queries, keys, and values come from?
- A
Queries and keys come from positions, while values come from vocabulary indices
- B
All three come from the decoder's masked self-attention scores
- C
Queries come from decoder states, while keys and values come from encoder outputs
- D
Queries come from encoder outputs, while keys and values come from decoder states
Correct answer
CQueries come from decoder states, while keys and values come from encoder outputs
Explanation
The decoder state determines what information it is seeking, so it provides queries. The encoder output provides the keys and values that can be searched.
- A
- 46
Why was the Transformer more efficient to train than recurrent sequence models?
- A
It represented every document with a single learned scalar
- B
It avoided all matrix multiplications in its attention layers
- C
It removed sequential recurrence and allowed more computation to run in parallel
- D
It trained only on adjacent word pairs rather than full sequences
Correct answer
CIt removed sequential recurrence and allowed more computation to run in parallel
Explanation
Unlike an RNN, a Transformer can compute attention for all positions together, making better use of GPUs and enabling faster training on large amounts of data.
- A
- 47
What major development did Transformer efficiency help enable in NLP?
- A
The return to exclusively hand-designed syntactic features
- B
The elimination of word representations from language models
- C
Large-scale pre-training on substantial amounts of data and computation
- D
The restriction of language models to short, fixed two-word inputs
Correct answer
CLarge-scale pre-training on substantial amounts of data and computation
Explanation
Parallelizability made it practical to train large models on massive datasets, contributing to the rise of Transformer-based pre-training.
- A
- 48
What is a major computational drawback of standard self-attention?
- A
Its memory and computation grow quadratically with sequence length
- B
It requires more sequential steps than a standard RNN
- C
It cannot process more than one attention head at a time
- D
Its computation grows exponentially with vocabulary size only
Correct answer
AIts memory and computation grow quadratically with sequence length
Explanation
Because self-attention computes all pairwise interactions, the attention-score matrix has n2 entries for a sequence of length n.
- A
- 49
Why can long documents be difficult for standard Transformers?
- A
Positional embeddings automatically delete every word after the first sentence
- B
Transformers cannot represent relationships between words in different sentences
- C
The encoder must use recurrence for every document longer than one paragraph
- D
The quadratic attention cost can make the required memory and computation infeasible
Correct answer
DThe quadratic attention cost can make the required memory and computation infeasible
Explanation
For long sequences, the n×n attention matrix becomes very large, creating substantial memory and computational demands.
- A
- 50
Why have researchers explored alternatives to absolute positional embeddings?
- A
Absolute embeddings prevent self-attention from computing any dot products
- B
Relative methods are required because word embeddings contain no lexical information
- C
Relative relationships may represent sequence structure more naturally than absolute indices
- D
Absolute embeddings can be used only in recurrent models
Correct answer
CRelative relationships may represent sequence structure more naturally than absolute indices
Explanation
The absolute index of a word may be less informative than its relative position or structural relationship to other words, motivating alternative positional representations.
- A

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