🌍 Deep Learning · subject

Deep Learning Transformers and Attention Syllabus

The Transformers and Attention syllabus for Deep Learning in full: 5 chapters and 20 topics, every one listed below, plus 58 Transformers and Attention flashcards with answers.

5Chapters
20Topics
58Flashcards

Transformers and Attention syllabus: all 5 chapters

Expand any chapter to see its topics and sub-topics.

  1. The Transformer Architecture

    4 topics
    • Self-Attention
    • Multi-Head Attention
    • Positional Encoding
    • Encoder and Decoder Stacks
  2. Pretrained Language Models

    4 topics
    • BERT and Masked Language Modeling
    • GPT and Autoregressive Models
    • T5 and Encoder-Decoder Models
    • Tokenizers (BPE, WordPiece, SentencePiece)
  3. Large Language Models

    5 topics
    • Scaling Laws and Emergent Abilities
    • In-Context Learning and Prompting
    • Fine-Tuning and Alignment
    • Parameter-Efficient Fine-Tuning
    • Retrieval-Augmented Generation
  4. Vision and Multimodal Transformers

    3 topics
    • Vision Transformers (ViT)
    • CLIP and Contrastive Pretraining
    • Multimodal Architectures
  5. Efficient Attention

    4 topics
    • FlashAttention
    • Sparse and Linear Attention
    • KV Caching
    • Mixture of Experts

Deep Learning Transformers and Attention flashcards — 58 questions with answers

  1. What is self-attention, and what three vectors are computed for each input token?

    Self-attention lets each token attend to all tokens in the sequence to build context-aware representations. For each token it computes a Query ($Q$), Key ($K$), and Value ($V$) vector by multiplying the input embedding with learned weight matrices $W_Q$, $W_K$, $W_V$.

  2. Write the scaled dot-product attention formula.

    $$\text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^{T}}{\sqrt{d_k}}\right)V$$ where $d_k$ is the dimension of the key vectors.

  3. Why is the dot product scaled by $\frac{1}{\sqrt{d_k}}$ in attention?

    For large $d_k$, the dot products grow large in magnitude, pushing the softmax into regions with extremely small gradients. Dividing by $\sqrt{d_k}$ keeps the variance around 1, stabilizing gradients and training.

  4. What is the time and memory complexity of standard self-attention with respect to sequence length $n$?

    $O(n^{2}\,d)$ time and $O(n^{2})$ memory, because every token attends to every other token, producing an $n \times n$ attention matrix.

  5. What is multi-head attention and why is it used?

    Multi-head attention runs $h$ separate attention operations (heads) in parallel on different learned linear projections of $Q$, $K$, $V$, then concatenates and projects the results. It lets the model jointly attend to information from different representation subspaces and positions.

  6. Give the formula for multi-head attention.

    $$\text{MultiHead}(Q,K,V) = \text{Concat}(\text{head}_1,\dots,\text{head}_h)W^{O}$$ where $\text{head}_i = \text{Attention}(QW_i^{Q}, KW_i^{K}, VW_i^{V})$.

  7. In the original Transformer, with model dimension $d_{model}=512$ and $h=8$ heads, what is the dimension per head?

    Each head uses $d_k = d_v = \frac{d_{model}}{h} = \frac{512}{8} = 64$. This keeps total computation similar to single-head attention at full dimensionality.

  8. Why do Transformers need positional encoding?

    Self-attention is permutation-invariant and has no inherent notion of token order. Positional encodings inject information about the absolute or relative position of tokens so the model can use sequence order.

  9. Write the sinusoidal positional encoding formulas from the original Transformer.

    $$PE_{(pos,2i)} = \sin\!\left(\frac{pos}{10000^{2i/d_{model}}}\right), \quad PE_{(pos,2i+1)} = \cos\!\left(\frac{pos}{10000^{2i/d_{model}}}\right)$$ where $pos$ is the position and $i$ is the dimension index.

  10. Contrast absolute, learned, and relative (e.g., RoPE) positional encodings.

    Absolute (sinusoidal) uses fixed functions of position; learned encodings train a position embedding table; relative encodings (e.g., RoPE, ALiBi) encode the distance between tokens rather than absolute positions, generalizing better to longer sequences.

  11. What are the two main sublayers in each Transformer encoder block, and how are they wrapped?

    Each encoder block has (1) a multi-head self-attention sublayer and (2) a position-wise feed-forward network. Each sublayer is wrapped with a residual (skip) connection followed by layer normalization: $\text{LayerNorm}(x + \text{Sublayer}(x))$.

  12. How does a Transformer decoder block differ from an encoder block?

    A decoder block has three sublayers: (1) masked multi-head self-attention (causal masking prevents attending to future tokens), (2) cross-attention over the encoder outputs, and (3) a feed-forward network, each with residual connections and layer norm.

  13. What is the position-wise feed-forward network in a Transformer, and its typical hidden size?

    It is applied identically to each position: $$\text{FFN}(x) = \max(0, xW_1 + b_1)W_2 + b_2$$ Typically the inner dimension is $4\times$ the model dimension (e.g., $2048$ for $d_{model}=512$).

  14. What is causal (autoregressive) masking in decoder self-attention?

    A mask sets the attention scores for all future positions to $-\infty$ before the softmax, so position $i$ can only attend to positions $\leq i$. This preserves the autoregressive property during training and generation.

  15. Compare Pre-LN and Post-LN Transformer architectures.

    Post-LN (original) applies LayerNorm after the residual addition; it can be unstable and needs warmup. Pre-LN applies LayerNorm inside the residual branch before the sublayer, giving more stable gradients and easier training of deep models, at a slight quality cost.

  16. What is BERT and what is its architectural type?

    BERT (Bidirectional Encoder Representations from Transformers) is an encoder-only Transformer that produces bidirectional contextual representations. It is pretrained then fine-tuned for downstream tasks like classification and question answering.

  17. Describe the Masked Language Modeling (MLM) objective used to pretrain BERT.

    Randomly mask ~15% of input tokens and train the model to predict the original tokens from bidirectional context. Of the chosen tokens, 80% are replaced with [MASK], 10% with a random token, and 10% kept unchanged.

  18. What was BERT's second pretraining objective, and what did later work find about it?

    Next Sentence Prediction (NSP): predict whether sentence B follows sentence A. Later work (e.g., RoBERTa) found NSP largely unhelpful and removed it, training only with MLM on longer sequences.

  19. What special tokens does BERT use and what are their roles?

    [CLS] is prepended and its final hidden state is used for classification/pooling; [SEP] separates sentence segments and marks the end; [MASK] marks masked tokens; segment embeddings distinguish sentence A from B.

  20. What is GPT and what pretraining objective does it use?

    GPT (Generative Pretrained Transformer) is a decoder-only autoregressive model trained with causal language modeling: predict the next token given all previous tokens, maximizing $$\sum_{t} \log P(x_t \mid x_{<t}).$$

Show the other 38 Transformers and Attention flashcards
  1. Contrast BERT and GPT in terms of directionality and typical use.

    BERT is an encoder-only, bidirectional model best for understanding tasks (classification, NER, QA) via fine-tuning. GPT is a decoder-only, unidirectional (left-to-right) model best for generation and few-shot in-context learning.

  2. What does 'autoregressive' mean for a language model?

    The model factorizes the joint probability of a sequence as a product of conditional next-token probabilities $P(x) = \prod_t P(x_t \mid x_{<t})$, generating one token at a time conditioned on previously generated tokens.

  3. What is T5 and its unifying framing of NLP tasks?

    T5 (Text-to-Text Transfer Transformer) is an encoder-decoder model that casts every NLP task as text-to-text: input text in, target text out (e.g., translation, classification, summarization all become string-to-string), using a task prefix.

  4. What pretraining objective does T5 use?

    Span corruption (a denoising objective): contiguous spans of tokens are masked and replaced by unique sentinel tokens, and the model learns to generate the dropped spans as the target sequence.

  5. Compare encoder-only, decoder-only, and encoder-decoder Transformer architectures.

    Encoder-only (BERT): bidirectional, for understanding. Decoder-only (GPT): causal, for generation. Encoder-decoder (T5, original Transformer): encoder reads input bidirectionally, decoder generates output with cross-attention, ideal for seq2seq like translation.

  6. What problem do subword tokenizers solve compared to word-level tokenization?

    They handle out-of-vocabulary and rare words by breaking them into known subword units, keeping vocabulary size manageable while representing any string, including morphological variants and misspellings.

  7. How does Byte-Pair Encoding (BPE) build its vocabulary?

    Starting from characters/bytes, BPE iteratively counts adjacent symbol pairs and merges the most frequent pair into a new token, repeating until a target vocabulary size is reached. Merges are then applied greedily at inference.

  8. How does WordPiece differ from BPE in choosing merges?

    Instead of picking the most frequent pair, WordPiece (used by BERT) merges the pair that maximizes the likelihood of the training data, i.e., it selects the pair maximizing $\frac{\text{count}(xy)}{\text{count}(x)\,\text{count}(y)}$-style score.

  9. What makes SentencePiece distinctive as a tokenizer?

    SentencePiece treats the input as a raw stream (including spaces as a special symbol, e.g., '▁'), so it is language-agnostic and reversible, requiring no pre-tokenization. It can implement BPE or the unigram language model algorithm.

  10. What are neural scaling laws for language models?

    Empirical power-law relationships showing test loss decreases predictably as a power of model parameters $N$, dataset size $D$, and compute $C$: $$L(N) \approx \left(\frac{N_c}{N}\right)^{\alpha_N}$$ Loss falls smoothly and predictably as these scale up.

  11. What is the key finding of the Chinchilla scaling law?

    For a fixed compute budget, model size and training tokens should scale roughly equally; many earlier models were undertrained. Chinchilla recommends about 20 training tokens per parameter, and a smaller, longer-trained model outperformed larger undertrained ones.

  12. What are 'emergent abilities' of large language models?

    Capabilities (e.g., multi-step arithmetic, in-context reasoning) that are absent or near-random in smaller models but appear relatively abruptly once model scale crosses a threshold, and are not predictable by simple extrapolation of the loss curve alone.

  13. What is in-context learning (ICL)?

    The ability of a large model to perform a new task purely from examples and instructions given in the prompt at inference time, without any gradient updates or weight changes.

  14. Distinguish zero-shot, one-shot, and few-shot prompting.

    Zero-shot: only a task description, no examples. One-shot: exactly one demonstration example in the prompt. Few-shot: several demonstration examples in the prompt. More examples generally improve performance up to the context limit.

  15. What is chain-of-thought (CoT) prompting?

    Prompting the model to produce intermediate reasoning steps before the final answer (e.g., 'Let's think step by step'), which substantially improves performance on arithmetic, commonsense, and symbolic reasoning tasks, especially at large scale.

  16. What is the difference between fine-tuning and pretraining?

    Pretraining trains a model from scratch on massive unlabeled data with a self-supervised objective. Fine-tuning takes the pretrained model and further trains it (updating weights) on a smaller labeled or task-specific dataset to specialize it.

  17. What is instruction tuning?

    Fine-tuning a pretrained LLM on a diverse collection of tasks phrased as natural-language instructions with responses, so the model learns to follow instructions and generalizes to unseen instruction-formatted tasks in zero-shot settings.

  18. Describe the three stages of RLHF (Reinforcement Learning from Human Feedback).

    (1) Supervised fine-tuning on demonstration data; (2) train a reward model from human preference rankings of outputs; (3) optimize the policy against the reward model using RL, typically PPO, often with a KL penalty to stay close to the SFT model.

  19. What is DPO (Direct Preference Optimization) and how does it differ from RLHF?

    DPO directly optimizes the policy on preference pairs using a classification-style loss derived from the reward-model objective, eliminating the need to train a separate reward model or run RL/PPO. It is simpler and more stable while targeting the same preference-alignment goal.

  20. What is Parameter-Efficient Fine-Tuning (PEFT) and why is it used?

    PEFT adapts a large pretrained model by training only a small number of new or selected parameters while freezing most of the backbone. It drastically reduces memory, storage, and compute cost, and mitigates catastrophic forgetting, enabling many task-specific adapters per base model.

  21. How does LoRA (Low-Rank Adaptation) work?

    LoRA freezes pretrained weights $W$ and learns a low-rank update $\Delta W = BA$ where $B \in \mathbb{R}^{d \times r}$, $A \in \mathbb{R}^{r \times k}$, and $r \ll d,k$. The forward pass becomes $h = Wx + BAx$, so only $A$ and $B$ are trained, greatly reducing trainable parameters.

  22. What is QLoRA?

    QLoRA fine-tunes with LoRA adapters on top of a base model quantized to 4-bit (NF4), using techniques like double quantization and paged optimizers. It enables fine-tuning very large models on a single GPU with minimal quality loss.

  23. Name three families of PEFT methods besides LoRA.

    Adapter modules (small bottleneck layers inserted between Transformer sublayers), prompt/prefix tuning (learning soft continuous prompt vectors), and (IA)^3 / BitFit (scaling activations or training only bias terms).

  24. What is Retrieval-Augmented Generation (RAG)?

    RAG augments an LLM by retrieving relevant documents from an external knowledge source (often via vector similarity search) and conditioning generation on them, improving factual accuracy, enabling up-to-date knowledge, and reducing hallucination without retraining.

  25. Outline the main steps of a RAG pipeline.

    (1) Chunk and embed a document corpus into a vector store; (2) embed the user query; (3) retrieve top-$k$ similar chunks (e.g., by cosine similarity); (4) insert retrieved context into the prompt; (5) the LLM generates an answer grounded in that context.

  26. How does a Vision Transformer (ViT) adapt Transformers to images?

    ViT splits an image into fixed-size patches (e.g., $16\times16$), linearly embeds each patch into a token, adds positional embeddings and a learnable [class] token, then feeds the sequence into a standard Transformer encoder for classification.

  27. What is a key data requirement of ViTs compared to CNNs?

    ViTs lack the built-in inductive biases (locality, translation equivariance) of CNNs, so they need large-scale pretraining data (e.g., JFT-300M) to match or exceed CNNs; with limited data CNNs often perform better.

  28. What is CLIP and how is it trained?

    CLIP (Contrastive Language-Image Pretraining) jointly trains an image encoder and text encoder on image-caption pairs with a contrastive objective, maximizing cosine similarity of matched image-text embeddings and minimizing it for mismatched pairs within a batch (symmetric InfoNCE loss).

  29. How does CLIP enable zero-shot image classification?

    Class names are turned into text prompts (e.g., 'a photo of a {class}') and encoded; the image embedding is compared by cosine similarity to each class-text embedding, and the highest-similarity class is chosen, with no task-specific training.

  30. What is the contrastive InfoNCE-style loss objective used in contrastive pretraining?

    For a matched pair among $N$ candidates, minimize $$\mathcal{L} = -\log \frac{\exp(\text{sim}(z_i, z_i^{+})/\tau)}{\sum_{j=1}^{N} \exp(\text{sim}(z_i, z_j)/\tau)}$$ where $\tau$ is a temperature and $\text{sim}$ is cosine similarity.

  31. What are common strategies for fusing modalities in multimodal Transformer architectures?

    Early fusion (concatenate modality tokens into one Transformer with cross-modal self-attention), late fusion (separate encoders combined at the end), and cross-attention fusion (one modality attends to another, e.g., Flamingo's gated cross-attention injecting vision into a language model).

  32. How do multimodal LLMs typically connect a vision encoder to a language model?

    A frozen or trained vision encoder (often ViT/CLIP) produces image features that a projection/adapter module (e.g., a linear layer or Q-Former as in BLIP-2, or an MLP as in LLaVA) maps into the LLM's token embedding space so images become 'tokens' the LLM reads.

  33. What problem does FlashAttention solve and how?

    It removes the $O(n^{2})$ memory bottleneck of materializing the full attention matrix. FlashAttention is an IO-aware, exact attention algorithm that tiles $Q$, $K$, $V$ into SRAM blocks and uses online softmax to compute attention without ever writing the $n\times n$ matrix to HBM, giving large speedups and linear memory.

  34. Is FlashAttention an approximation of attention?

    No. FlashAttention computes exact attention (identical outputs to standard attention). Its gains come from reducing memory reads/writes to slow HBM via kernel fusion, tiling, and recomputation in the backward pass, not from approximating the softmax.

  35. What is sparse attention and how does it reduce complexity?

    Sparse attention restricts each token to attend to a subset of positions (e.g., local windows, strided, or global tokens as in Longformer/BigBird) instead of all $n$, reducing complexity from $O(n^{2})$ toward $O(n)$ or $O(n\log n)$ while retaining most modeling power.

  36. How does linear attention achieve $O(n)$ complexity?

    Linear attention replaces the softmax with a kernel feature map $\phi(\cdot)$ so attention becomes $\phi(Q)\big(\phi(K)^{T}V\big)$. By computing $\phi(K)^{T}V$ first (associativity), it avoids the $n\times n$ matrix, giving $O(n\,d^{2})$ time and memory linear in sequence length.

  37. What is Multi-Query Attention (MQA) / Grouped-Query Attention (GQA)?

    MQA shares a single Key/Value head across all Query heads, and GQA shares K/V among groups of query heads. Both shrink the KV cache and speed up autoregressive inference with little quality loss, interpolating between full multi-head (per-head KV) and single-head KV.

  38. Why is the KV cache used during autoregressive generation, and what is its memory cost?

    During generation, previously computed Key and Value vectors are cached so each new token only computes attention against stored K/V instead of recomputing them. Its memory grows linearly with sequence length and number of layers/heads, and often becomes the dominant inference memory cost, motivating MQA/GQA.

Deep Learning Transformers and Attention FAQ

What is in the Deep Learning Transformers and Attention syllabus?

Deep Learning Transformers and Attention is split into 5 chapters: The Transformer Architecture, Pretrained Language Models, Large Language Models, Vision and Multimodal Transformers and Efficient Attention. Together they contain 20 topics.

How many chapters are in Deep Learning Transformers and Attention?

5 chapters, containing 20 topics. The largest chapter is Large Language Models, with 5 topics.

Are there flashcards for Deep Learning Transformers and Attention?

Yes — a 58-card Transformers and Attention deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.