Transformers Cheatsheet

Core concepts from 'Attention Is All You Need' — architecture, attention mechanisms, and generation

📚 Learning Resources

Recommended reading order: go from top to bottom (1 to 6).
TopicSource
Good for setting the context for the problem set-up. Doesn't go into scaled dot product.
DeepLearning.AI
Excellent visual walkthrough of attention mechanism with matrix illustrations.
Jay Alammar
Hands-on tutorial building GPT from the ground up with detailed explanations.
Andrej Karpathy
Very readable and understandable reference implementation.
nanoGPT (Karpathy)
The foundational paper introducing the Transformer architecture.
arXiv (Vaswani et al.)
Line-by-line annotation of the original paper with working PyTorch code.
Harvard NLP

Why Transformers Matter

Transformers were revolutionary because they let language models attend to all parts of a sequence in parallel, making it much easier to learn long-range relationships than with older recurrent models. That parallelism also made training vastly more scalable on modern hardware, which unlocked the huge data and model sizes behind today's strongest language models.

vs. prior NLP models (RNNs, LSTMs):

  • Contextual understanding — each token learns which other tokens matter for interpreting it
  • Parallelization — can be optimized on GPU/TPUs (no sequential dependency)
  • Long-range dependencies — captures relationships across entire sequence
  • Stable gradients — avoids vanishing/exploding gradient problems

Transformer Architecture Types

ArchitectureHow it attendsIntuitionBest forExamples
Encoder-only (e.g., BERT)Bidirectional self-attention — each token attends to tokens on both left and rightBuilds deep contextual understanding of the full input by looking at the whole sentence at onceTasks where the goal is to interpret or label text rather than generate itsentiment classification, NER, search/ranking, information extraction
Decoder-only (e.g., GPT)Masked self-attention — each token can only attend to earlier tokensLearns to generate text one token at a time, always predicting what comes next from prior contextAutoregressive generation and open-ended text productionchatbots, story writing, code completion, next-token prediction
Encoder–Decoder (e.g., T5)Encoder uses bidirectional attention; decoder uses masked self-attention + cross-attention to encoder statesFirst reads and understands the input, then generates an output conditioned on that inputInput-to-output tasks where the model transforms one sequence into anothertranslation, summarization, question answering, paraphrasing

Example: Encoder–Decoder Architecture

The full Transformer encoder-decoder architecture diagram from 'Attention Is All You Need', showing stacked multi-head attention, feed-forward layers, add & norm, and positional encoding.

Encoder–Decoder architecture. From Vaswani et al., "Attention Is All You Need" (2017).

Pipeline: Input → Output

INPUT

Tokenization
Text → tokens (subwords)
Word Embeddings
Tokens → dense vectors
Positional Encoding
Add position info

OUTPUT

A decoder-only transformer produces a probability distribution over the vocabulary for the next token. The model must then use a decoding strategy to decide which token to output.

Greedy decoding
Always chooses the highest-probability next token. Simple and deterministic, but can be repetitive or overly rigid.
Top-k sampling
Samples from only the k most likely next tokens. Adds variety while avoiding very unlikely choices.
Top-p (nucleus) sampling
Samples from the smallest set of tokens whose cumulative probability reaches p. More adaptive than top-k because the candidate set changes based on model confidence.
Temperature
Adjusts how sharp or flat the probability distribution is before sampling. Lower temperature is more conservative; higher temperature is more random and diverse.

Other Architectural Design Choices

Residual Connections
Skip connections that add the layer's input directly to its output. Prevents gradient degradation (vanishing gradients) in deep networks by giving gradients a direct path backwards.
Layer Normalization
Normalizes each token's representation across the embedding dimension. Stabilizes training by reducing internal covariate shift and enabling higher learning rates.

Attention Mechanism

The attention mechanism acts as a dynamic spotlight, allowing the model to rank the importance of every word in a sentence simultaneously, regardless of distance.

The implementation uses a retrieval metaphor — each token asks: "what information do I need?" and fetches it from the sequence:

Query (Q)
The search term — the current token looking for context.
Key (K)
The index label — how every other token describes itself.
Value (V)
The content — the information passed along if the Key matches the Query.

Q, K, V are learned linear projections of token representations:

Q = X·WQ,   K = X·WK,   V = X·WV

The projection matrices WQ, WK, WV are learned during model training via backpropagation — the model discovers which projections produce the most useful attention patterns.

Self-Attention vs Cross-Attention

Self-attention
Q, K, V all come from the same sequence. Each token attends to every other token in the same sequence.
Cross-attention
Q comes from the decoder, K and V come from the encoder. Lets the decoder attend to the full encoded input context.

Attention Score Computation

scorei,j = (Qi · Kj) / √dk
αi,j = softmax(score) over j
outi = Σj αi,j · Vj

The output matrix O (one row per token) encodes all contextual information — each row is a weighted sum of value vectors, capturing what each token should "know" given the full context.

Why divide by √dk?

Dividing by √dk scales the variance of the attention scores back to 1:

Var(Q·K / √dk) = (1/dk) · Var(Q·K) = (1/dk) · dk = 1

This is critical because without scaling, high-dimensional dot products explode in magnitude, saturating softmax into a hard one-hot distribution — which effectively zeros out the gradients and freezes the model's ability to learn through backpropagation.

Matrix View (Q, K, V and Scaled Dot Product)

Matrix calculation of self-attention showing XWQ, XWK, XWV and softmax(QK^T/sqrt(dk))V.

Illustration adapted from Jay Alammar's The Illustrated Transformer.

Multi-Head Attention

Multiple attention heads run in parallel, each learning different relationship patterns (syntax, coreference, long-range links). Outputs are concatenated and projected back down.

Head Dimension Rule
If embedding size is X and you use H heads, each head operates on dimension X/H. The Q, K, and V matrices are split along the embedding dimension before per-head attention is computed — so each head sees a distinct slice of the representation.

Masking

A lower-triangular matrix mask is applied during causal (decoder) attention. Each position can only attend to itself and earlier positions — future tokens are masked with −∞ before softmax, ensuring the model cannot look ahead during training or generation.

Key Code: Causal Self-Attention (nanoGPT)

Source: karpathy/nanoGPT `model.py`

Python
def forward(self, x):
    B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)

    # calculate query, key, values for all heads in batch and move head forward to be the batch dim
    q, k, v  = self.c_attn(x).split(self.n_embd, dim=2)
    k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
    q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
    v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)

    # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
    if self.flash:
        # efficient attention using Flash Attention CUDA kernels
        y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0, is_causal=True)
    else:
        # manual implementation of attention
        att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
        att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
        att = F.softmax(att, dim=-1)
        att = self.attn_dropout(att)
        y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
    y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side

    # output projection
    y = self.resid_dropout(self.c_proj(y))
    return y

MLP / Feed-Forward Network (FFN)

What it is

After each attention layer, a feed-forward network (FFN) is applied independently to each token's representation. It transforms the contextual information in the attention output matrix into the model's final probability distribution over all tokens in the vocabulary.

Why is it added?

Adds nonlinearity and expressiveness
Self-attention mostly mixes information across tokens. The FFN applies nonlinear transformations so the model can learn richer patterns, not just weighted averages.
Processes each token deeply
After attention gathers context, the FFN transforms that contextualized representation into more useful features — almost like a per-token "thinking step."
Expands model capacity
The FFN projects to a larger hidden dimension and back down, giving the transformer much of its parameter count and allowing it to store and compute complex knowledge efficiently.
Based on 'Attention Is All You Need' (Vaswani et al., 2017)