liveBook · Manning

Transformer encoder layer

As explained in Inside Deep Learning: Math, Algorithms, Models

A transformer block that processes an input sequence with self-attention and a feedforward step, and can be stacked repeatedly.

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.

How Inside Deep Learning: Math, Algorithms, Models covers it

How deep it goes
Explains self-attention, residual structure, stacking, and positional encoding, but does not detail the linear step internally.
Examples
Uses sentiment classification, a three-layer PyTorch classifier, and a Transformer-versus-GRU accuracy plot.
What it assumes
Assumes multi-head attention and positional encodings, while distinguishing self-attention from externally conditioned attention.
What you can do after
Apply it via PyTorch's nn.TransformerEncoder and stack encoder layers for sequence classification.
How it connects
Connects self-attention, multi-head attention, residual connections, layer normalization, positional encoding, decoders, and autoregressive models.

Also explained in

Compare how 3 books explain Transformer encoder layer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Inside Deep Learning: Math, Algorithms, Models. The section links point to the parts of the book it draws on.