A Transformer encoder helps a computer understand sequences like sentences by looking at all parts at once, not just step-by-step.
Transformer encoder in PyTorch
torch.nn.TransformerEncoder(encoder_layer, num_layers, norm=None)encoder_layer is a single Transformer encoder block that you repeat.
num_layers is how many times you stack the encoder blocks.
encoder_layer = torch.nn.TransformerEncoderLayer(d_model=512, nhead=8) transformer_encoder = torch.nn.TransformerEncoder(encoder_layer, num_layers=6)
encoder_layer = torch.nn.TransformerEncoderLayer(d_model=256, nhead=4) transformer_encoder = torch.nn.TransformerEncoder(encoder_layer, num_layers=3, norm=torch.nn.LayerNorm(256))
This code builds a Transformer encoder with 2 layers. It processes a random sequence of length 10 with 16 features. The output shape shows the sequence length, batch size, and feature size stay the same.
import torch import torch.nn as nn # Define a single encoder layer encoder_layer = nn.TransformerEncoderLayer(d_model=16, nhead=4) # Stack 2 layers to build the encoder transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=2) # Create a sample input: sequence length=10, batch size=1, feature size=16 input_seq = torch.rand(10, 1, 16) # Pass input through the transformer encoder output = transformer_encoder(input_seq) # Print output shape and first vector print('Output shape:', output.shape) print('First output vector:', output[0, 0])
The input to TransformerEncoder must have shape (sequence_length, batch_size, feature_size).
TransformerEncoderLayer uses multi-head attention to look at all parts of the sequence together.
Adding normalization (LayerNorm) can help training be more stable.
Transformer encoder processes sequences by looking at all parts at once.
It stacks multiple encoder layers for deeper understanding.
Input shape is (sequence length, batch size, features) and output shape matches input shape.
Practice
Solution
Step 1: Understand the Transformer encoder role
The Transformer encoder looks at all parts of the input sequence at once using self-attention, unlike sequential models.Step 2: Compare options with this role
Only To process sequences by attending to all positions simultaneously describes this behavior correctly. Other options describe unrelated tasks.Final Answer:
To process sequences by attending to all positions simultaneously -> Option CQuick Check:
Transformer encoder = attends all positions [OK]
- Confusing encoder with decoder
- Thinking it generates sequences
- Mixing with convolutional networks
Solution
Step 1: Identify the correct PyTorch class for Transformer encoder layer
The class to create a Transformer encoder layer is torch.nn.TransformerEncoderLayer.Step 2: Check the parameters
d_model and nhead are required parameters for this class, matching torch.nn.TransformerEncoderLayer(d_model=512, nhead=8).Final Answer:
torch.nn.TransformerEncoderLayer(d_model=512, nhead=8) -> Option BQuick Check:
Encoder layer class = TransformerEncoderLayer [OK]
- Using DecoderLayer instead of EncoderLayer
- Confusing convolution or linear layers with Transformer layers
- Missing required parameters
import torch from torch.nn import TransformerEncoderLayer layer = TransformerEncoderLayer(d_model=16, nhead=4) input_tensor = torch.rand(10, 32, 16) # (seq_len, batch_size, features) output = layer(input_tensor)
Solution
Step 1: Understand input shape format
The input tensor shape is (sequence length, batch size, features) = (10, 32, 16).Step 2: TransformerEncoderLayer output shape
The output shape matches the input shape for TransformerEncoderLayer.Final Answer:
(10, 32, 16) -> Option DQuick Check:
Output shape = input shape (seq_len, batch, features) [OK]
- Swapping batch size and sequence length
- Confusing feature dimension order
- Assuming output shape changes
import torch from torch.nn import TransformerEncoder, TransformerEncoderLayer layer = TransformerEncoderLayer(d_model=64, nhead=8) encoder = TransformerEncoder(layer, num_layers=2) input_tensor = torch.rand(20, 16, 64) output = encoder(input_tensor)
Solution
Step 1: Check input tensor shape
Input shape is (seq_len=20, batch_size=16, features=64), which is correct for TransformerEncoder.Step 2: Verify other parameters
nhead=8 is valid as 64 is divisible by 8; dropout is optional; no error in code.Final Answer:
The input tensor shape is correct; no error -> Option AQuick Check:
Input shape (seq_len, batch, features) is correct [OK]
- Swapping batch and sequence dimensions
- Thinking dropout is mandatory
- Assuming nhead must be 1
Solution
Step 1: Check d_model and nhead parameters
d_model must match feature size (32), and nhead must divide d_model (4 divides 32). import torch from torch.nn import TransformerEncoder, TransformerEncoderLayer layer = TransformerEncoderLayer(d_model=32, nhead=4) encoder = TransformerEncoder(layer, num_layers=3) input_tensor = torch.rand(15, 8, 32) output = encoder(input_tensor) matches this.Step 2: Verify input tensor shape and num_layers
Input shape should be (seq_len=15, batch=8, features=32). import torch from torch.nn import TransformerEncoder, TransformerEncoderLayer layer = TransformerEncoderLayer(d_model=32, nhead=4) encoder = TransformerEncoder(layer, num_layers=3) input_tensor = torch.rand(15, 8, 32) output = encoder(input_tensor) uses this shape and 3 layers as required.Final Answer:
Code snippet in option A correctly creates and processes the input -> Option AQuick Check:
d_model=32, nhead=4, input shape correct [OK]
- Swapping batch and sequence dimensions
- Using nhead that doesn't divide d_model
- Mismatching d_model and input feature size
Ready to prove it?
Pass the test and this pattern moves unknown
