Skip to content
module

Transformer

12 members
lucid.models.text.transformer

Original Transformer family — Vaswani et al., 2017 (encoder-decoder seq2seq).

Language ModelingSequence ClassificationToken Classification
Paper

Vaswani, Ashish, et al. "Attention Is All You Need." Advances in Neural Information Processing Systems, 2017, pp. 5998–6008.

Overview

The Transformer replaces the recurrence of RNN-based seq2seq models with scaled dot-product attention, enabling fully parallel sequence processing. For query/key/value matrices Q∈RTq×dkQ \in \mathbb{R}^{T_q \times d_k}, K∈RTk×dkK \in \mathbb{R}^{T_k \times d_k}, and V∈RTk×dvV \in \mathbb{R}^{T_k \times d_v}, attention is

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V,\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left( \frac{Q K^\top}{\sqrt{d_k}} \right) V,

where the 1/dk1/\sqrt{d_k} factor counteracts the variance of dot products in high dimensions and keeps softmax gradients well-conditioned.

Multi-head attention runs hh parallel attention heads on learned projections of (Q,K,V)(Q, K, V) into dk=dv=dmodel/hd_k = d_v = d_{\text{model}} / h subspaces, concatenates the outputs, and applies a final linear:

MultiHead⁡(Q,K,V)=Concat⁡(head1,…,headh) WO,headi=Attention⁡(QWiQ,KWiK,VWiV).\operatorname{MultiHead}(Q, K, V) = \operatorname{Concat}(\text{head}_1, \dots, \text{head}_h)\, W^O, \qquad \text{head}_i = \operatorname{Attention}(Q W_i^Q, K W_i^K, V W_i^V).

Each encoder layer stacks multi-head self-attention and a position-wise feed-forward network (with hidden width dff=2048d_{\text{ff}}=2048), wrapped in residual connections and post-LayerNorm. Each decoder layer adds causal self-attention over previously generated targets and cross-attention over the encoder output.

Position information is injected via sinusoidal positional encodings of fixed (untrained) frequencies, which generalise to sequence lengths unseen during training. The paper's base model (N=6N=6 encoder/decoder layers, dmodel=512d_{\text{model}}=512, h=8h=8) achieves state-of-the-art WMT 2014 En-De / En-Fr BLEU while training in a fraction of the time of prior recurrent and convolutional seq2seq systems — the architectural foundation for essentially every modern language model.

Classes

Functions