Get startedGet started for free

The encoder transformer body

Your encoder-only transformer body is almost complete! It's time to combine the InputEmbeddings, PositionalEncoding, and EncoderLayer classes you've created previously into a TransformerEncoder class.

This exercise is part of the course

Transformer Models with PyTorch

View Course

Exercise instructions

  • Define the token embedding, positional encoding, and encoder layers (use the list comprehension to create num_layers encoder layers).
  • Perform the forward pass through these layers.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

class TransformerEncoder(nn.Module):
    def __init__(self, vocab_size, d_model, num_layers, num_heads, d_ff, dropout, max_seq_length):
        super().__init__()
        # Define the embedding, positional encoding, and encoder layers
        self.embedding = ____(vocab_size, d_model)
        self.positional_encoding = ____(d_model, max_seq_length)
        self.layers = nn.____([____(d_model, num_heads, d_ff, dropout) for _ in range(num_layers)])

    def forward(self, x, src_mask):
        # Perform the forward pass through the layers
        x = self.____(x)
        x = self.____(x)
        for layer in ____:
            x = layer(x, src_mask)
        return x
Edit and Run Code