Attention and the transformer

Translation from English to Italian with a transformer built from its parts — attention, masks, positional encodings and pre-norm residual blocks.

What you'll learn
  • Compute scaled dot-product attention by hand and explain the √d_k
  • Build the padding and causal masks a translation model needs
  • Assemble encoder and decoder blocks, and audit them for silent bugs

Recurrent networks read a sentence one word at a time and squeeze everything into one hidden state. A transformer lets every word look directly at every other word. 07_transformer_translation builds one from scratch and trains it on the English–Italian opus_books corpus.

Attention

Each token is projected three ways: a query (what am I looking for?), a key (what do I contain?) and a value (what do I pass on?). A token’s output is the average of all values, weighted by how well its query matches each key:

\[\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{Q K^{\mathsf T}}{\sqrt{d_k}}\right) V\]
attention_scores = (query @ key.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
    attention_scores.masked_fill_(mask == 0, -1e9)
attention_scores = attention_scores.softmax(dim=-1)
return (attention_scores @ value), attention_scores

The \(\sqrt{d_k}\) keeps the scores’ spread independent of the head size: a dot product of two random \(d_k\)-vectors has variance \(d_k\), and without the division large heads would push the softmax into near one-hot outputs with vanishing gradients.

Attention weights for a six-word sentence with toy 4-d embeddings. Each row is a query and sums to 1; the readout shows that row's raw scores and softmax. Switch to the causal mask to see what a decoder may look at: nothing to the right of the diagonal.

Notice that the two “the” rows are identical without a mask: attention by itself has no idea of word order. The positional encoding fixes that by adding a fixed pattern of sines and cosines of different frequencies to each embedding, so the same word at different positions gets a different vector.

Multi-head attention runs \(h = 8\) attentions in parallel on 64-dimensional slices of the 512-dimensional embedding, then concatenates and mixes them with w_o. The view(..., h, d_k).transpose(1, 2) in forward is lesson 1’s stride trick doing the split for free.

Masks

dataset.py builds two masks. The padding mask hides [PAD] tokens, which fill every sentence up to seq_len = 350. The causal mask lets decoder position \(i\) see only positions \(\le i\), so training can feed the whole target sentence at once without letting the model peek at the word it is about to predict:

def causal_mask(size):
    mask = torch.triu(torch.ones((1, size, size)), diagonal=1).type(torch.int)
    return mask == 0

Encoder, decoder and the residual blocks

The encoder-decoder transformer from model.py. Encoder: source tokens, embedding times square root of 512, positional encoding, then six blocks of LayerNorm, multi-head self-attention, residual add, LayerNorm, feed-forward 512 to 2048 to 512, residual add, then a final LayerNorm. Decoder: target tokens so far, embedding and positional encoding, six blocks of masked self-attention, cross-attention whose keys and values come from the encoder output, and feed-forward, each preceded by LayerNorm and followed by a residual add; then a final LayerNorm and a linear plus log-softmax producing next-token probabilities. The encoder-decoder transformer from model.py. Encoder: source tokens, embedding times square root of 512, positional encoding, then six blocks of LayerNorm, multi-head self-attention, residual add, LayerNorm, feed-forward 512 to 2048 to 512, residual add, then a final LayerNorm. Decoder: target tokens so far, embedding and positional encoding, six blocks of masked self-attention, cross-attention whose keys and values come from the encoder output, and feed-forward, each preceded by LayerNorm and followed by a residual add; then a final LayerNorm and a linear plus log-softmax producing next-token probabilities.
As written in model.py: LayerNorm comes before each sublayer (pre-norm), and the encoder's final output provides the keys and values of every decoder cross-attention.

Counting parameters: one encoder block has 3,150,340 (four 512×512 projections with biases, 1,050,624, plus the 2,099,712-parameter feed-forward network), a decoder block 4,200,966 (one more attention). Six of each make 44.1 million, before the embeddings and the output projection, whose size depends on the vocabularies.

Two lines in model.py deserve a second look:

class LayerNormalization(nn.Module):
    def forward(self, x):
        ...
        return self.alpha * (x - mean) / (std - self.eps) + self.bias

class ResidualConnection(nn.Module):
    def __init__(self, dropout: float) -> None:
        super().__init__()
        self.dropout = nn.Dropout()

The first should be std + self.eps: the epsilon is there to keep the division safe when the standard deviation is tiny, and subtracting it does the opposite — for a constant input the denominator becomes \(-10^{-6}\). The second ignores its argument, and nn.Dropout() defaults to \(p = 0.5\): every residual branch in the model drops half its activations during training instead of the configured 10%. Both are one-word fixes: std + self.eps and nn.Dropout(dropout).

A detail in train.py works by coincidence: the loss ignores padding with ignore_index=tokenizer_src.token_to_id('[PAD]'), the source tokenizer’s id, applied to target labels. Both tokenizers list the special tokens in the same order, so the ids agree — but tokenizer_tgt is the one that should be named.

06_monocular_depth_pytorch sits between these folders: its readme describes depth estimation with Intel’s DPT-large, but g_transformers.py currently holds a three-line Hugging Face sentiment-analysis pipeline, so there is no depth code to discuss yet.

Try it yourself. Fix the two lines above, then build the model with build_transformer(1000, 1000, 350, 350) and count its parameters. Predict the total first: 44,107,840 for the blocks and final norms, plus two 1000×512 embeddings and a 512→1000 projection with bias. Finally, feed it a batch and check that each row of a decoder self-attention map is zero to the right of the diagonal.

View source on GitHub →