liveBook · Manning

Transformer encoder

As explained in Deep Learning with R, Third Edition

A Transformer encoder is an architectural component that transforms input sequence representations using self-attention and feedforward processing.

A Transformer encoder converts a sequence of vectors into context-aware representations: self-attention lets each element use information from the others, while positional encoding preserves word order. Used alone, it supports sequence or set tasks such as text classification; paired with a decoder, it supplies representations for sequence-to-sequence prediction. section 20.1.6

Binary classification from integer sequences

A compact Keras model embeds tokens and positions, applies an encoder, pools the sequence, and predicts a binary label: inputs <- x <- keras_input(c(seq_length), dtype = "int64") x <- TokenAndPositionEmbedding(vocab_size, seq_length, embed_dim)(x) x <- TransformerEncoder(intermediate_dim = 256L, num_heads = 8L)(x) x <- layer_global_max_pooling_1d()(x) outputs <- layer_dense(units = 1, activation = "sigmoid")(x) model <- keras_model(inputs, outputs) model |> compile(optimizer = "adamw", loss = "binary_crossentropy")

A Transformer encoder fits into larger architectures in two common ways:

  • Use the encoder alone when one input sequence must produce a classification or other sequence-level result. section 20.1.6
  • Feed encoder outputs to a Transformer decoder for sequence-to-sequence tasks such as translation or question answering. section 20.1.6
  • Provide positional information explicitly: attention relates sequence elements as a set and otherwise cannot distinguish their order. section 15.3.4

How Deep Learning with R, Third Edition covers it

How deep it goes
Defines contextual and order-aware processing and demonstrates Keras composition, but does not derive attention mathematically.
Examples
Demonstrates binary classification from integer sequences and English-to-Spanish translation with encoder-decoder layers.
What it assumes
Assumes sequence inputs and token embeddings, while demonstrating positional information and encoder placement from the architecture itself.
What you can do after
Build it from scratch with Keras by embedding tokens, applying TransformerEncoder, pooling outputs, and compiling a classifier.
How it connects
Connects self-attention, positional encoding, embeddings, Transformer decoders, sequence-to-sequence learning, RNNs, and 1D convolutional networks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with R, Third Edition. The section links point to the parts of the book it draws on.