Transformer Neural Networks Explained
- 22Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is the purpose of word embedding in a Transformer?
22 questions
- 1
What is the purpose of word embedding in a Transformer?
Model answer
Word embedding converts words (or tokens) into numerical vectors that a neural network can process.
Explanation
Neural networks require numerical inputs, so word embedding maps each token in the vocabulary to a dense vector of real numbers using a simple network with learned weights.
- 2
In the word embedding process, how is a token like 'let's' converted into numbers?
Model answer
A one-hot vector (1 for the token, 0 for others) is multiplied by learned weights to produce embedding values; each connection has a weight, and the activation function is typically an identity function.
Explanation
For example, input token 'let's' has a 1 in its position and zeros elsewhere. The weighted sums from the connections to the activation functions become the embedding numbers. Identity activation means output equals weighted sum.
- 3
Why are the same word embedding weights reused for each token in the input sentence?
Model answer
Reusing the same weights allows the Transformer to handle sentences of different lengths and process all tokens in parallel.
Explanation
A single embedding network is copied for each token, so the same set of weights is applied to every token regardless of its position. This enables parallel computation because each token can be processed independently with shared weights.
- 4
What problem does positional encoding solve in a Transformer?
Model answer
Positional encoding provides information about the order or position of words in the sequence, which the Transformer needs because self-attention is permutation-invariant.
Explanation
Without positional encoding, the model would treat sequences with the same words in different orders as identical. Positional encoding adds unique signals to each word's embedding to distinguish word order.
- 5
How are positional encoding values generated in the method described?
Model answer
They are generated using alternating sine and cosine functions of different frequencies; different embedding dimensions use different frequencies.
Explanation
For each embedding dimension, a sine or cosine squiggle (function) is defined with a specific frequency. The positional value for a given word at position p and dimension i is sin(p/100002i/d) or cos(p/100002i/d), where d is the embedding dimension. Higher dimensions use lower frequencies, resulting in unique position sequences.
- 6
How is positional encoding combined with word embeddings?
Model answer
The positional encoding values are added directly to the word embedding values element-wise.
Explanation
For each token, the embedding vector and the positional encoding vector are summed to produce a combined representation that carries both semantic and positional information.
- 7
What is the purpose of self-attention in a Transformer?
Model answer
Self-attention allows each word to attend to all other words in the input, enabling the model to capture contextual relationships (e.g., associating 'it' with 'pizza').
Explanation
Self-attention computes similarity scores between every pair of words in the sequence. These scores determine how much each word should contribute to the representation of every other word, providing context-aware encodings.
- 8
Describe the steps to compute self-attention for a single word. Include the roles of queries, keys, and values.
Model answer
First, compute query, key, and value vectors for each word via linear transformations. Then calculate dot product similarity between the query of the word and keys of all words (including itself). Apply softmax to get attention weights. Multiply each value vector by its attention weight and sum the weighted values to produce the self-attention output.
Explanation
Queries represent what the word is looking for, keys represent what other words offer, and values are the actual information to pass. The dot product similarity measures how relevant each key is to the query, softmax normalizes these scores into probabilities, and the weighted sum of values aggregates information from all words.
- 9
How is similarity between a query and a key computed in self-attention?
Model answer
Similarity is computed using the dot product of the query vector and the key vector.
Explanation
The dot product qcdotk=sumqiki yields a scalar that measures alignment. A larger positive value indicates greater similarity. This dot product may be scaled (e.g., divided by sqrtdk) to prevent large values in softmax.
- 10
What does the softmax function do in the self-attention mechanism?
Model answer
Softmax converts similarity scores into a probability distribution (values between 0 and 1 that sum to 1), indicating the percentage of each word to use in encoding the current word.
Explanation
Softmax preserves the relative order of scores but squashes them to a valid probability range. This allows the model to focus strongly on some words (e.g., 100% on itself) and ignore others (0%) based on relevance.
- 11
Why are the weight matrices for queries, keys, and values shared across all input tokens in self-attention?
Model answer
Sharing weights allows parallel computation and flexibility with input length, as the same transformation is applied to each token independently.
Explanation
With shared weights, each token's query, key, and value are computed using the same linear projections. This means that adding more tokens does not require new parameters, and the calculations for all tokens can be done simultaneously, speeding up training and inference.
- 12
What is multi-head attention?
Model answer
Multi-head attention stacks multiple self-attention cells (heads) with different weight sets, allowing each head to capture different types of relationships among words.
Explanation
The original Transformer used 8 parallel self-attention heads. Each head independently computes attention using its own queries, keys, and values. The outputs of all heads are concatenated and linearly transformed. This enables the model to jointly attend to information from different representation subspaces.
- 13
What are residual connections and why are they used in Transformers?
Model answer
Residual connections add the input of a layer to its output (e.g., adding positional encoding to self-attention output). They ease training by allowing gradients to flow directly and preserving information from earlier layers.
Explanation
By adding the original input to the output (like x+extLayer(x)), the layer can focus on learning a residual (the change) rather than the full mapping. This helps deep networks avoid vanishing gradients and retain word embedding/positional information.
- 14
What is the purpose of encoder-decoder attention in the decoder?
Model answer
Encoder-decoder attention allows the decoder to focus on relevant parts of the input sentence, ensuring important words from the encoder are not lost during translation.
Explanation
This mechanism works like self-attention but the query comes from the decoder, while the keys and values come from the encoder's output. It computes which encoder positions are most relevant to the current decoder step, enabling the decoder to attend to the source sentence appropriately.
- 15
How does encoder-decoder attention differ from self-attention in terms of key and value sources?
Model answer
In encoder-decoder attention, the queries come from the decoder, but the keys and values come from the encoder (the encoded input sentence).
Explanation
Self-attention uses the same source for queries, keys, and values (either all from encoder or all from decoder). Encoder-decoder attention mixes sources: the decoder's representation is used to query the encoder's representations, enabling cross-sequence attention.
- 16
Describe the process of encoder-decoder attention for a single decoder step.
Model answer
The decoder's current representation is transformed into a query. The encoder's output is transformed into keys and values. Dot product similarity is computed between the query and all keys, softmax provides weights, and weighted sum of encoder values yields the attention output.
Explanation
This is analogous to self-attention but with the keys/values from the encoder. The weights for queries, keys, and values in encoder-decoder attention are distinct from those used in self-attention. The output is added via a residual connection to preserve information from earlier decoder layers.
- 17
What token is typically used to start the decoding process in the described Transformer?
Model answer
The EOS (end-of-sequence) token is commonly used to start decoding, though SOS (start-of-sequence) is also possible.
Explanation
The decoder begins with the EOS token as the first input. Its embedding and positional encoding are processed through self-attention, encoder-decoder attention, and a fully connected layer to produce the first translated word. The process repeats by feeding the predicted word back into the decoder until EOS is output again.
- 18
How does the decoder select the output word (e.g., 'vamos') from the vector representation?
Model answer
The decoder's output vector is passed through a fully connected (linear) layer followed by a softmax to produce a probability distribution over the output vocabulary; the word with the highest probability is selected.
Explanation
The fully connected layer maps the decoder representation (e.g., 2 values) to a vector of size equal to the output vocabulary (e.g., 4). Softmax converts these scores into probabilities. The token with the maximum probability (e.g., 'vamos') is chosen as the translation.
- 19
When does the decoder stop generating tokens?
Model answer
The decoder stops when it outputs the EOS (end-of-sequence) token.
Explanation
The model is trained to predict the EOS token to mark the end of the translation. After the EOS token is produced, generation halts. In the example, after 'vamos', the decoder outputs EOS, signaling completion.
- 20
How are the weights in a Transformer optimized during training?
Model answer
Weights are initialized randomly and optimized using backpropagation with known input-output pairs (e.g., English phrases and their Spanish translations).
Explanation
Backpropagation computes gradients of a loss function (e.g., cross-entropy) with respect to all weights and adjusts them iteratively to minimize the loss. This process, called training, determines the optimal values for embedding weights, attention matrices, and fully connected layers.
- 21
What additional technique did the original Transformer use to improve training stability and performance?
Model answer
They applied layer normalization after each sub-layer (e.g., after positional encoding, self-attention) and scaled the dot product attention by dividing by sqrtdk where dk is the dimension of the key vectors.
Explanation
Layer normalization normalizes activations across the feature dimension, reducing covariate shift. Scaling the dot product prevents the softmax from entering regions with extremely small gradients when dk is large, improving gradient flow for long sequences.
- 22
Besides layer normalization and scaled dot-product, what other component can be added to a Transformer for increased capacity?
Model answer
Additional feed-forward neural networks with hidden layers can be added to both the encoder and decoder after the attention sub-layers.
Explanation
These feed-forward networks consist of two linear transformations with a ReLU activation in between, applied position-wise. This adds more learnable parameters, allowing the model to capture more complex patterns. The original Transformer used such networks in each encoder and decoder block.

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