Edd's Knowledge Base

Attention mechanisms solve a core limitation of the encoder-decoder RNN: the entire input sequence is compressed into a fixed-size context vector, which the decoder then uses for all output steps. With attention, the decoder can selectively focus on different parts of the encoder’s output at each decoding step.

The Development Arc

The lecture frames the evolution as 4 explicit stages, each building on the last:

StageArchitectureKey idea
1RNN with AttentionDecoder attends over all encoder states instead of just the last one
2RNN with Self-AttentionEach encoder hidden state attends over other states in the same sequence
3Attention without RNNCross-attention between encoder and decoder, but no recurrence
4Self-Attention without RNNEvery layer is pure self-attention — this is the Transformer

Each step addresses the limitations of the previous:

  • RNN alone: sequential computation, can’t parallelize, long-term forgetting.
  • RNN + Attention: decoder learns where to look, but the RNN itself is still sequential.
  • RNN + Self-Attention: richer encoder representations, but still sequential.
  • Transformer: fully parallel, no recurrence, attention does everything.

Attention in Seq2Seq (RNN + Attention)

In a standard Seq2Seq model, the decoder only looks at its current hidden state. With attention, it additionally consults all encoder hidden states, weighted by relevance.

Complexity

ModelParameters per step
Without attention
With attention

= input length, = output length. Each decoder step computes weights over all encoder states.

Key rule: Do NOT re-use attention weights computed in a previous decoder step.

Query, Key, Value Abstraction

Component”What it means”Source
Query”What am I looking for?”Decoder hidden state
Key”What do I have to offer?”Each encoder hidden state
Value”The actual content I return”Each encoder hidden state


Self-Attention

Self-attention applies the attention mechanism to a single sequence — the query, key, and value all come from the same sequence.

What it enables:

  • Each token can attend to every other token in the same sequence.
  • The model builds richer, context-aware representations.
  • Less likely to forget earlier parts of the sequence.

Example: In “The FBI is chasing a criminal on the run”, when encoding “run”, self-attention allows the model to attend to “FBI”, “chasing”, and “criminal”.

Attention vs. Self-Attention

Attention (Seq2Seq)Self-Attention
Needs decoder?Yes (two sequences)No (one sequence)
Use caseMachine translationAny sequence task
ScopeCross-sequenceWithin-sequence

Single-Head Self-Attention

Three learned parameter matrices: , , .

where , , .


Multi-Head Self-Attention

Run independent single-head self-attention layers in parallel, each with its own . Concatenate all outputs.

  • Total parameter matrices: (Q, K, V per head).
  • Output shape: if each head outputs a vector → multi-head output is .
  • Different heads can specialize in different types of relationships (syntax, coreference, proximity, etc.).
# Keras MultiHeadAttention layer
mha = keras.layers.MultiHeadAttention(num_heads=8, key_dim=64)
output = mha(query=x, key=x, value=x)  # self-attention: all three are the same x

Self-Attention Without RNN (The Bridge to Transformers)

This is the conceptual leap that makes the Transformer feel inevitable.

The question to ask: “If self-attention already lets each token attend to all others in the sequence, why do we need the RNN at all?”

  • The RNN’s job was to accumulate context across time steps.
  • Self-attention does this directly — in a single operation, every token can look at every other token.
  • The RNN is now redundant as a context aggregator.

Removing the RNN gives you:

  • Full parallelism — no sequential dependency between steps.
  • No vanishing gradient through time — attention weights are direct connections.
  • Unlimited effective context window — every token attends to every other token equally.

The only thing lost is the notion of position — RNNs inherently encode order by processing left to right. Transformers solve this with positional encodings added to the input embeddings, injecting order information back in explicitly.

In short: Self-attention without RNN = Transformer encoder. The Transformer isn’t magic — it’s what you get when you ask “what if we only use self-attention?”


The Transformer

The Transformer is a Seq2Seq model built entirely from attention and dense layers — no recurrence.

Why Remove the RNN?

  • RNNs are sequential: cannot be computed before — no parallelism.
  • RNNs still suffer from long-term forgetting even with attention.
  • Attention-only computation is fully parallelizable.

Transformer Encoder

  • Stack of 6 identical blocks.
  • Each block: Multi-Head Self-Attention (8 heads) + Dense Layer (+ residual connections & layer norm).
  • Input shape: → Output shape: (shape-preserving so blocks can be stacked).

Transformer Decoder

  • Stack of 6 identical blocks.
  • Each block has 3 sublayers:
    1. Masked Multi-Head Self-Attention — attends to the decoder’s own previous outputs (masked to prevent attending to future tokens).
    2. Multi-Head Attention — Keys & Values come from encoder output; Queries come from sublayer 1.
    3. Dense Layer.
  • Input: (decoder) + (encoder output) → Output: .

Transformer as Machine Translation

  1. Encoder processes the full source sentence.
  2. Decoder generates the target sentence one token at a time.
  3. Decoding starts with a [START] token, stops at [STOP].
  4. Both special tokens are part of the vocabulary and learned during training.
# Minimal Transformer encoder block in Keras
class TransformerEncoderBlock(keras.layers.Layer):
    def __init__(self, embed_dim, num_heads, ff_dim, **kwargs):
        super().__init__(**kwargs)
        self.attn = keras.layers.MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim // num_heads)
        self.ffn = keras.Sequential([
            keras.layers.Dense(ff_dim, activation='relu'),
            keras.layers.Dense(embed_dim),
        ])
        self.norm1 = keras.layers.LayerNormalization()
        self.norm2 = keras.layers.LayerNormalization()
 
    def call(self, x, training=False):
        attn_out = self.attn(x, x)
        x = self.norm1(x + attn_out)
        ffn_out = self.ffn(x)
        return self.norm2(x + ffn_out)

BERT (Bidirectional Encoder Representations from Transformers)

BERT is a method for pre-training the Transformer encoder on unlabeled text, producing powerful general-purpose representations that can be fine-tuned for downstream tasks.

  • Trained on English Wikipedia (~2.5 billion words) + BookCorpus.
  • Does not require manually labeled data.
  • Fully bidirectional — attends to left and right context simultaneously.
  • See BERT for the architecture, input representation, fine-tuning, and results.

Pre-Training Tasks

Task 1 — Masked Language Modeling (MLM)

  • 15% of tokens are selected for prediction; most (80%) are replaced with [MASK], some (10%) with a random token, and some (10%) are left unchanged.
  • The model predicts the original masked words using a Softmax classifier.
  • Loss: Cross-Entropy.

Task 2 — Next Sentence Prediction (NSP)

  • Input: [CLS] Sentence A [SEP] Sentence B.
  • Target: True (consecutive) or False (random pairing).
  • 50% real pairs, 50% random pairs.
  • A binary classifier is applied to the [CLS] token output.
  • Loss: Binary Cross-Entropy.

Combined Training:

Both tasks are trained simultaneously in a single gradient descent step.

# Fine-tuning BERT with HuggingFace + Keras
from transformers import TFBertModel, BertTokenizer
import tensorflow as tf
 
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
bert = TFBertModel.from_pretrained('bert-base-uncased')
 
inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
outputs = bert(**inputs)
 
# CLS token representation for classification
cls_embedding = outputs.last_hidden_state[:, 0, :]  # shape: (batch, 768)
logits = tf.keras.layers.Dense(2)(cls_embedding)

The Original Paper: Attention Is All You Need

Vaswani et al. (2017) introduced the Transformer for machine translation. Details beyond the architecture sketch above:

Sublayer wrapper. Every sublayer (attention or feed-forward) is wrapped as , which is why input and output shapes must match.

Base model hyperparameters.

ParameterValue
Layers (encoder and decoder each)6
Model width 512
Attention heads 8
Per-head dimension 64
Feed-forward inner width 2048

Splitting 512 dimensions across 8 heads keeps the cost of multi-head attention close to a single head of full width.

Positional encoding. Fixed sinusoids are added to the token embeddings, so each position gets a unique pattern and relative offsets can be expressed as linear functions of it:

Why self-attention beat recurrence (n = sequence length, d = representation width):

Layer typeComplexity per layerSequential operationsMax path length between tokens
Self-attention
Recurrent

Self-attention is cheaper than recurrence when , which holds for typical sentence lengths. Its quadratic cost in is what later motivated efficiency work such as KV Cache and long-context variants.

Results. On WMT 2014 the big model reached 28.4 BLEU (English-German) and 41.8 BLEU (English-French), at a fraction of the training cost of prior best models.

Decoder details. The decoder’s self-attention is masked (scores for future positions are set to before the softmax) and its output embeddings are offset by one position, so the prediction for position can depend only on known outputs at positions before . A third sublayer, encoder-decoder (cross) attention, takes its queries from the previous decoder layer and its keys and values from the final encoder output, so every decoder layer reads the same encoder output.

Embeddings and vocabulary. The two embedding layers and the pre-softmax linear transformation share the same weight matrix, and in the embedding layers the weights are multiplied by . English-German used a shared byte-pair vocabulary of about 37,000 tokens; English-French used a 32,000 word-piece vocabulary.

Regularization. Dropout with rate 0.1 is applied to each sublayer’s output before it is added and normalized, and to the sums of the embeddings and positional encodings in both stacks. Label smoothing of 0.1 is also used.

Positional encoding experiments. The authors also tried learned positional embeddings and found nearly identical results. They chose the sinusoidal version because it may let the model extrapolate to sequence lengths longer than those seen in training.

Source: Attention Is All You Need (Vaswani et al., 2017). For a visual walkthrough see The Illustrated Transformer.


From Paper to Code: The Annotated Transformer

The Annotated Transformer (Harvard NLP; original by Sasha Rush, 2022 update by Austin Huang and colleagues) is a line-by-line PyTorch implementation of the paper, with the text reordered and commented. It is the quickest way to see how each idea above becomes a few lines of code; working snippets are collected in Transformer Snippets.

Concept to code map

Paper conceptCode componentWhat to notice
Scaled dot-product attentionattention(query, key, value, mask)Masked positions are set to a large negative score before the softmax
Multi-head attentionMultiHeadedAttention(h, d_model)Four d_model x d_model linear layers (Q, K, V, output); heads are a reshape, not separate modules
Sublayer wrapperSublayerConnectionResidual add plus layer norm; the code normalizes before the sublayer (pre-norm) for simplicity
Position-wise feed-forwardPositionwiseFeedForward(d_model, d_ff)Two linear layers with a ReLU, applied to each position independently
Embeddings and softmaxEmbeddings, GeneratorEmbedding output is scaled by ; the generator is a linear layer plus log-softmax
Position informationPositionalEncodingSinusoids precomputed once and stored as a non-trainable buffer
Causal maskingsubsequent_mask(size)Lower-triangular matrix so position cannot see positions after
Whole modelmake_model(src_vocab, tgt_vocab, N=6, d_model=512, d_ff=2048, h=8, dropout=0.1)An EncoderDecoder that wires encoder, decoder, embeddings, and generator

The training recipe (often skipped, but required for the model to converge)

IngredientValueWhy
OptimizerAdam, , , Lower than the usual 0.999 reacts faster to gradient changes
Learning rate, warmup 4000 stepsLinear warmup, then inverse-square-root decay; a large rate too early destabilizes attention
Label smoothingHurts perplexity but improves accuracy and BLEU
Dropout0.1 on sublayer outputs and on embeddings plus positional encodingsRegularization of the base model
BatchingAbout 25,000 source and 25,000 target tokens per batch, grouped by lengthBatch by tokens rather than sentences so padding stays low
DataWMT 2014 English-German, about 4.5M pairs, shared BPE vocabulary of about 37,000 tokensShared vocabulary allows tying source, target, and output embeddings

Extras the walkthrough points to but does not implement: subword (BPE) preprocessing, shared embeddings, beam search, and averaging the last few checkpoints for an ensembling effect.

Suggested way to use it: run the synthetic copy task first (a tiny model learning to repeat its input) to confirm the pipeline trains, then move to the Multi30k German-English example, then read the attention visualizations (encoder self-attention, decoder self-attention, decoder source attention) to see what the heads learn.

Source: The Annotated Transformer, Harvard NLP.


  • Word2Vec - Static word embeddings that fed the input layer of earlier NLP models.
  • RNNs & LSTMs - The sequential architectures that Transformers replace.
  • Autoencoders - Another encoder-decoder architecture (for reconstruction, not generation).
  • Large Language Models - GPT-style models built on the Transformer decoder.
  • BERT - Pre-training the Transformer encoder bidirectionally.
  • GPT-1 - Pre-training the Transformer decoder left-to-right, then fine-tuning.
  • Transformer Snippets - PyTorch code for the components described here.
  • RNNs & CNNs for Text Classification - NLP grounding for sequence models.