AlgoViz

Attention Is All You Need

medium 40 min

The 2017 paper that introduced the Transformer.

Attention, multi-head, masks, positions and a KV cache in plain Python

Read it, run it, change a line and run it again.

Loading editor…

Runs here with no libraries. All vectors are our own small examples, so you can check every number by hand. The numpy variant does the same with matrices.

The same in python (numpy)
# The same with numpy, in matrix form. Shapes: X (n, d_model), W_q/W_k/W_v (d_model, d_model), W_o (d_model, d_model).import numpy as npdef softmax(x, axis=-1):    x = x - x.max(axis=axis, keepdims=True)    e = np.exp(x)    return e / e.sum(axis=axis, keepdims=True)def attention(Q, K, V, causal=False):    d_k = Q.shape[-1]    scores = Q @ K.swapaxes(-1, -2) / np.sqrt(d_k)          # (..., n, n)    if causal:        n = scores.shape[-1]        scores = np.where(np.tril(np.ones((n, n), bool)), scores, -np.inf)    return softmax(scores) @ Vdef multi_head(X, W_q, W_k, W_v, W_o, h, causal=False):    n, d = X.shape    split = lambda M: M.reshape(n, h, d // h).transpose(1, 0, 2)   # (h, n, d/h)    heads = attention(split(X @ W_q), split(X @ W_k), split(X @ W_v), causal)    return heads.transpose(1, 0, 2).reshape(n, d) @ W_odef positional_encoding(n, d):    pos = np.arange(n)[:, None]    i = np.arange(0, d, 2)[None, :]    angle = pos / 10000 ** (i / d)    pe = np.zeros((n, d))    pe[:, 0::2], pe[:, 1::2] = np.sin(angle), np.cos(angle)    return perng = np.random.default_rng(0)n, d, h = 5, 8, 2X = rng.normal(size=(n, d)) + positional_encoding(n, d)W = [rng.normal(size=(d, d)) / np.sqrt(d) for _ in range(4)]print(multi_head(X, *W, h=h, causal=True).shape)   # (5, 8)
The same in python (PyTorch)
# PyTorch ships the same operation. is_causal=True applies the decoder mask.import torchimport torch.nn.functional as Fq = torch.tensor([[[2.0, 0.0]]])                                   # (batch, 1 query, d_k)k = torch.tensor([[[2.0, 0.0], [0, 1], [0, 2], [1, 1], [1, 0]]])   # (batch, 5 keys, d_k)v = torch.tensor([[[1.0, 0.0], [0, 0], [0, 1], [0, 0], [0, 0]]])print(F.scaled_dot_product_attention(q, k, v))                      # about [[0.62, 0.04]]mha = torch.nn.MultiheadAttention(embed_dim=512, num_heads=8, batch_first=True)x = torch.randn(1, 10, 512)mask = torch.nn.Transformer.generate_square_subsequent_mask(10)out, weights = mha(x, x, x, attn_mask=mask)print(out.shape, weights.shape)                                     # (1, 10, 512) (1, 10, 10)