An encoder block transforms a sequence without external context. It applies self-attention, where the same sequence supplies queries, keys, and values, then a residual linear or feedforward step. Layer normalization and residual connections support the block, which can be stacked for greater depth. section 12.5.2
Build the block around these implementation choices:
- Use self-attention first; unlike a decoder, the encoder does not require an external sequence. section 12.5.2
- Repeat the block to create a deeper encoder; six repetitions are given as a common default. section 12.5.2
- Add positional encodings because the block has no explicit recurrent time connections. section 12.5.2
PyTorch classifier
A classifier can instantiate nn.TransformerEncoder with a TransformerEncoderLayer and three layers, then apply attention pooling and a prediction head.


