An explorable explanation of Attention Is All You Need (Vaswani et al., 2017)

Build a Transformer, one block at a time

Every large language model you have used is built on one idea from a 2017 paper. Scroll down and the architecture assembles itself, block by block. Click any block to open its explanation, the exact formulas with every symbol explained, and a small visual you can try.

Running example: translating the black cat sleeps on the mat into French, le chat noir dort sur le tapis. You only need basic matrix multiplication.

QueryKeyValueAttentionEncoderDecoder
Scroll to start building

    Cheat sheet

    Every formula on one screen, plus the paper's hyperparameters.

    Input
    $$X = E[t]\sqrt{d_{\text{model}}} + PE$$
    Positional encoding
    $$PE_{(p,2i)} = \sin\!\big(p/10000^{2i/d}\big)$$ $$PE_{(p,2i+1)} = \cos\!\big(p/10000^{2i/d}\big)$$
    Scaled dot-product attention
    $$\text{softmax}\!\left(\frac{\htmlClass{cq}{Q}\htmlClass{ck}{K}^{\top}}{\sqrt{d_k}} + M\right)\htmlClass{cv}{V}$$
    Multi-head
    $$\text{Concat}(\text{head}_1..\text{head}_h)W^{O}$$ $$\text{head}_i = \text{Attn}(QW_i^Q, KW_i^K, VW_i^V)$$
    Add & Norm
    $$\text{LayerNorm}(x + \text{Sublayer}(x))$$ $$\gamma\odot\frac{x-\mu}{\sqrt{\sigma^2+\epsilon}}+\beta$$
    Feed-forward
    $$\max(0, xW_1 + b_1)W_2 + b_2$$
    Output
    $$\text{softmax}(h_t W_{\text{vocab}} + b)$$
    Loss
    $$-\frac{1}{T}\sum_t \log P(y_t^* \mid y^*_{<t}, x)$$
    Learning rate schedule
    $$d_{\text{model}}^{-0.5}\cdot\min\!\big(s^{-0.5},\ s\cdot w^{-1.5}\big)$$

    \(s\) is the step, \(w = 4000\) warmup steps

    Hyperparameters of the base model

    SymbolMeaningBaseBig
    \(N\)layers in the encoder and in the decoder66
    \(d_{\text{model}}\)width of every token vector5121024
    \(h\)attention heads816
    \(d_k = d_v\)width per head, \(d_{\text{model}}/h\)6464
    \(d_{ff}\)hidden width of the feed-forward network20484096
    \(P_{drop}\)dropout rate0.10.3
    \(\epsilon_{ls}\)label smoothing0.10.1
    optimizerAdam, β1 = 0.9, β2 = 0.98, ε = 1e-9
    parameters65M213M

    Shapes at a glance

    TensorShape
    Input \(X\)n × 512
    \(W_i^Q, W_i^K, W_i^V\)512 × 64
    \(Q_i, K_i, V_i\)n × 64
    Attention weights per headn × n
    Concat of headsn × 512
    \(W^O\)512 × 512
    \(W_1\) / \(W_2\)512 × 2048 / 2048 × 512
    Logitsn × |V|

    Source: Vaswani, A. et al. Attention Is All You Need, NeurIPS 2017, arXiv:1706.03762. Decoder-only models such as GPT keep only the right half of the diagram (masked self-attention and FFN), while BERT keeps only the left half.

    Resources

    The only links on this page. Each opens in a new tab.