Bird
Raised Fist0
NLPml~20 mins

Encoder-decoder with attention in NLP - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Attention Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
What is the main purpose of the attention mechanism in an encoder-decoder model?

In an encoder-decoder model for sequence-to-sequence tasks, what does the attention mechanism primarily help with?

AIt replaces the decoder with a simpler feedforward network.
BIt allows the decoder to focus on different parts of the input sequence dynamically during generation.
CIt speeds up training by skipping the encoder step.
DIt reduces the size of the input sequence by compressing it into a fixed-length vector.
Attempts:
2 left
💡 Hint

Think about how the decoder decides which parts of the input to use when producing each output word.

Predict Output
intermediate
2:00remaining
Output shape of attention weights in a simple encoder-decoder

Given the following PyTorch code snippet for scaled dot-product attention weights calculation, what is the shape of attention_weights?

NLP
import torch

batch_size = 2
seq_len_enc = 5
seq_len_dec = 3
hidden_dim = 4

encoder_outputs = torch.rand(batch_size, seq_len_enc, hidden_dim)
decoder_hidden = torch.rand(batch_size, seq_len_dec, hidden_dim)

# Compute attention scores
scores = torch.bmm(decoder_hidden, encoder_outputs.transpose(1, 2)) / (hidden_dim ** 0.5)

# Apply softmax to get attention weights
attention_weights = torch.softmax(scores, dim=2)

print(attention_weights.shape)
A(3, 2, 5)
B(2, 5, 3)
C(2, 3, 5)
D(2, 3, 4)
Attempts:
2 left
💡 Hint

Recall that torch.bmm batch-multiplies matrices of shape (batch, n, m) and (batch, m, p) resulting in (batch, n, p).

Model Choice
advanced
2:00remaining
Choosing the correct attention type for long input sequences

You want to build an encoder-decoder model for translating very long sentences. Which attention mechanism is best to handle long input sequences efficiently?

ASelf-attention only in the decoder without encoder-decoder attention.
BNo attention, just use the last encoder hidden state as context.
CGlobal attention that attends to all encoder outputs at every decoding step.
DLocal attention that attends only to a small window of encoder outputs near the current decoding position.
Attempts:
2 left
💡 Hint

Consider the computational cost and relevance of distant input tokens for very long sequences.

Hyperparameter
advanced
2:00remaining
Effect of increasing attention head count in multi-head attention

In a transformer encoder-decoder model, what is the effect of increasing the number of attention heads in multi-head attention?

AIt allows the model to jointly attend to information from different representation subspaces at different positions.
BIt reduces the model's capacity by splitting the hidden dimension into smaller parts.
CIt always decreases training time because each head runs independently.
DIt removes the need for positional encoding.
Attempts:
2 left
💡 Hint

Think about why multiple attention heads might help the model understand different aspects of the input.

🔧 Debug
expert
2:00remaining
Identifying the cause of NaN loss in an encoder-decoder with attention training

During training of an encoder-decoder model with attention, the loss suddenly becomes NaN after a few epochs. Which of the following is the most likely cause?

AThe attention scores are not normalized properly before softmax, causing numerical instability.
BThe optimizer learning rate is too low, causing the loss to diverge to NaN.
CThe model uses dropout layers, which always cause NaN values during training.
DThe input sequences are too short, causing the model to overfit and produce NaN.
Attempts:
2 left
💡 Hint

Consider what can cause softmax to produce invalid values and how attention scores are computed.

Practice

(1/5)
1. What is the main purpose of the attention mechanism in an encoder-decoder model?
easy
A. To randomly select input tokens for the decoder
B. To help the model focus on relevant parts of the input sequence when generating each output token
C. To speed up the training by skipping some input tokens
D. To reduce the size of the input data before encoding

Solution

  1. Step 1: Understand the role of attention in sequence models

    Attention helps the decoder look at specific parts of the input sequence instead of the whole input equally.
  2. Step 2: Identify the correct purpose

    The attention mechanism focuses on relevant input parts to improve output quality.
  3. Final Answer:

    To help the model focus on relevant parts of the input sequence when generating each output token -> Option B
  4. Quick Check:

    Attention = Focus on input parts [OK]
Hint: Attention means focusing on important input parts [OK]
Common Mistakes:
  • Thinking attention reduces input size
  • Believing attention speeds training by skipping tokens
  • Assuming attention randomly selects tokens
2. Which of the following is the correct way to compute the attention weights in an encoder-decoder model?
easy
A. Apply softmax to the dot product of decoder hidden state and encoder outputs
B. Add encoder outputs and decoder outputs directly without normalization
C. Multiply decoder output by a random matrix
D. Use the maximum value of encoder outputs as attention weight

Solution

  1. Step 1: Recall attention weight calculation

    Attention weights are usually computed by taking the dot product between the decoder's current hidden state and each encoder output, then applying softmax to get probabilities.
  2. Step 2: Match the correct formula

    Apply softmax to the dot product of decoder hidden state and encoder outputs correctly describes this process with softmax on dot product.
  3. Final Answer:

    Apply softmax to the dot product of decoder hidden state and encoder outputs -> Option A
  4. Quick Check:

    Attention weights = softmax(dot product) [OK]
Hint: Attention weights come from softmax of dot products [OK]
Common Mistakes:
  • Skipping softmax normalization
  • Adding outputs without weighting
  • Using random matrices instead of encoder states
3. Given the following simplified code snippet for attention weights calculation, what will be the output shape of attention_weights?
encoder_outputs = torch.randn(5, 10, 20)  # batch=5, seq_len=10, hidden=20
decoder_hidden = torch.randn(5, 20)       # batch=5, hidden=20

# Compute scores
scores = torch.bmm(encoder_outputs, decoder_hidden.unsqueeze(2)).squeeze(2)
# Apply softmax
attention_weights = torch.softmax(scores, dim=1)
medium
A. [5, 10]
B. [5, 20]
C. [10, 20]
D. [5, 1]

Solution

  1. Step 1: Analyze tensor shapes in batch matrix multiplication

    encoder_outputs shape is (5, 10, 20), decoder_hidden.unsqueeze(2) shape is (5, 20, 1). The batch matrix multiplication results in shape (5, 10, 1).
  2. Step 2: Remove last dimension and apply softmax

    After squeezing, scores shape is (5, 10). Applying softmax along dim=1 keeps shape (5, 10).
  3. Final Answer:

    [5, 10] -> Option A
  4. Quick Check:

    Attention weights shape = (batch, seq_len) = [5, 10] [OK]
Hint: Attention weights shape = batch size x input sequence length [OK]
Common Mistakes:
  • Confusing hidden size with sequence length
  • Forgetting to squeeze last dimension
  • Applying softmax on wrong axis
4. You implemented an encoder-decoder with attention model but notice the attention weights are always uniform (equal values). What is the most likely cause?
medium
A. The batch size is too small
B. The encoder outputs have different dimensions than decoder hidden states
C. The model uses too many layers in the encoder
D. The softmax function is missing after computing attention scores

Solution

  1. Step 1: Understand uniform attention weights meaning

    If attention weights are uniform, the model treats all input tokens equally without focusing on any part.
  2. Step 2: Identify missing softmax effect

    Without softmax, raw scores are not normalized into probabilities, causing uniform or incorrect weights.
  3. Final Answer:

    The softmax function is missing after computing attention scores -> Option D
  4. Quick Check:

    Missing softmax = uniform attention weights [OK]
Hint: Always apply softmax to attention scores [OK]
Common Mistakes:
  • Ignoring normalization step
  • Blaming encoder size or batch size
  • Assuming model depth causes uniform weights
5. In a machine translation task using an encoder-decoder with attention, the model struggles to translate long sentences accurately. Which modification can best help improve performance?
hard
A. Remove the attention mechanism to simplify the model
B. Reduce the encoder hidden size to speed up training
C. Use multi-head attention to capture different aspects of the input simultaneously
D. Increase the batch size without changing the model

Solution

  1. Step 1: Identify challenges with long sentences

    Long sentences require the model to focus on multiple relevant parts; single attention may miss some details.
  2. Step 2: Understand multi-head attention benefits

    Multi-head attention allows the model to attend to different parts of the input in parallel, improving context understanding.
  3. Final Answer:

    Use multi-head attention to capture different aspects of the input simultaneously -> Option C
  4. Quick Check:

    Multi-head attention = better long sentence handling [OK]
Hint: Multi-head attention improves focus on complex inputs [OK]
Common Mistakes:
  • Thinking smaller hidden size helps accuracy
  • Removing attention reduces model power
  • Assuming batch size alone fixes long sentence issues