1. Learn
  2. /
  3. Courses
  4. /
  5. Transformer Models with PyTorch

Connected

Exercise

Adding methods to the MultiHeadAttention class

In this exercise, you'll build the rest of the MultiHeadAttention class from the ground up by defining four methods:

  • .split_heads(): split and transform the input embeddings between the attention heads
  • .compute_attention(): calculate the scaled dot-product attention weights multiplied by the values matrix
  • .combine_heads(): transform the attention weights back into the same shape as the input embeddings, x
  • .forward(): call the other methods to pass the input embeddings through each process

torch.nn has been imported as nn, torch.nn.functional is available as F, and torch is also available.

Instructions 1/4

undefined XP
    1
    2
    3
    4
  • Split the input embeddings, x, between the attention heads by reshaping them to (batch_size, seq_length, self.num_heads, self.head_dim).