interviewpath
  • 0day streak
  • 10total XP
  • Level 1
0/7

Unit 7 · ML & applied AI · Lesson 7 of 13

Transformers, attention and language-model objectives

The transformer is the architecture behind current language and multimodal models. You need to explain attention, masking, tokenization, positional information and pretraining objectives precisely, because so much applied AI and ML work, and the interview questions about it, builds on them.
About 5 hFocus mode

Step 1: Learn the ideas

  • Queries, keys, values and scaled dot-product attention
  • Multi-head attention and the output projection
  • Causal masks and padding masks
  • Transformer block: residuals, normalization placement, MLP
  • Encoder-only, decoder-only and encoder-decoder models
  • Tokenization: BPE, byte-level BPE and vocabulary size
  • Positional information: sinusoidal, learned and RoPE (awareness)
  • Objectives: next-token prediction, masked LM, teacher forcing, perplexity
  • Decoding: greedy, temperature, top-k and top-p
  • Cost: quadratic attention and the KV cache (awareness)

Why it matters

Applied AI work assumes you understand what a model computes when you send it a prompt: why context length costs what it costs, why a tokenizer mangles numbers, why a padding bug changes outputs. A standard research or ML engineering exercise is to write attention from scratch, with masks and shapes.

Core ideas

Attention. Each position produces a query, a key and a value by linear projections. With Q of shape (n, d_k), K of shape (m, d_k) and V of shape (m, d_v), Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V has shape (n, d_v): each output row is a convex combination of value rows, weighted by query-key similarity. If query and key components are roughly independent with unit variance, their dot product has variance d_k; dividing by sqrt(d_k) keeps the logits at unit scale so the softmax does not saturate and gradients do not vanish.

Multi-head attention. Split the model dimension into h heads, each with its own projections, attend in parallel, concatenate and project back. Heads can specialize (local syntax, copying, long-range links) at the same parameter cost as one full-width head. With batch B, tensors are typically shaped (B, h, n, d_head).

Masks. Masks act on the scores before the softmax by setting disallowed positions to a large negative value.

  • Causal mask: position i attends only to positions up to i, so training on every position in parallel matches left-to-right generation.
  • Padding mask: padded keys must be excluded, or real tokens attend to junk. A row with every key masked becomes NaN if negative infinity is used, which implementations must guard against.

The block and model families. A block applies attention and then a position-wise MLP (several times wider than the model dimension, with GELU or a gated variant such as SwiGLU), each wrapped in a residual connection with normalization. Most current LLMs normalize before each sublayer (pre-norm), which trains deep stacks more stably than the original post-norm layout, often with RMSNorm. Encoder-only models such as BERT see the whole input and suit classification, embeddings and reranking. Decoder-only models are causal and generate text. Encoder-decoder models (the original transformer, T5) encode an input and decode an output through cross-attention.

Tokenization. BPE starts from characters or bytes and repeatedly merges the most frequent adjacent pair in a training corpus, recording the merges in order; encoding replays them. Byte-level BPE starts from the 256 byte values, so any string can be encoded without unknown tokens. Consequences: common words become single tokens while rare words, identifiers, numbers and many non-English scripts split into several, which changes cost, usable context and arithmetic behavior. Leading spaces usually belong to tokens, so "cat" and " cat" differ. Vocabulary size trades sequence length against embedding and output-layer size.

Positional information. Without position information attention is permutation-equivariant: "dog bites man" and "man bites dog" contain the same tokens. Options: fixed sinusoidal encodings added to embeddings (the original paper); learned absolute position embeddings (BERT, GPT-2), which do not extend beyond the trained length; and rotary embeddings (RoPE), which rotate queries and keys by position-dependent angles so their dot product depends on relative offset. RoPE is common in recent open models, and context-extension methods rescale its frequencies.

Objectives. Causal language modeling minimizes the cross-entropy of each next token given the true prefix (teacher forcing). Perplexity, exp of the mean per-token loss, is comparable only across models with the same tokenizer and evaluation text. Masked language modeling (BERT) selects a fraction of input positions (15% in BERT), replaces most of them with a mask token, and predicts the originals from context on both sides; it yields strong encoders but no left-to-right generator.

Decoding and cost. Generation adds one token at a time: greedy, temperature-scaled sampling, top-k or top-p (nucleus). Materialized attention scores take O(n^2) memory per head and O(n^2 d) compute for sequence length n; IO-aware kernels avoid storing the full score matrix. During generation, a KV cache keeps past keys and values per layer, so each new token attends over the cache in time linear in context length, while cache memory grows with length and batch size.

Common misconceptions

  • "The sqrt(d_k) factor normalizes the output." It scales the logits before the softmax to prevent saturation.
  • "The causal mask matters only at inference." It is essential in training; without it the model sees the token it must predict.
  • "Tokens are words." They are learned subword pieces whose count varies with language, formatting and digits.
  • "Perplexity compares any two language models." Only with the same tokenizer and evaluation text.
  • "Masked and causal LM differ only in the mask." They train different capabilities: bidirectional representations versus left-to-right generation.

How to approach it

Implement attention with masks in a notebook and test it against the framework's fused attention on random padded batches. Train a small BPE tokenizer and inspect its segmentations. Read the original paper with D2L chapter 11 open. In interviews, write shapes on every line and explain each design choice by the failure it prevents.

Suggested order

  1. 1Read D2L 11.1 (Queries, Keys, and Values), 11.3 (Attention Scoring Functions) and 11.5 (Multi-Head Attention), implementing each code cell.
  2. 2Read the model architecture section of "Attention Is All You Need" (scaled dot-product and multi-head attention, positional encoding); skim the experiments.
  3. 3Read D2L 11.6 (Self-Attention and Positional Encoding), 11.7 (The Transformer Architecture) and 11.9 (Large-Scale Pretraining with Transformers).
  4. 4Read the BPE paper by Sennrich et al., then build a byte-level BPE tokenizer in the minbpe project.
  5. 5Read the pretraining section of the BERT paper to contrast masked language modeling with next-token prediction.
  6. 6Implement the CS336 Assignment 1 tokenizer, attention with RoPE and transformer LM against its unit tests, or write a small decoder-only model and compare your attention with torch.nn.functional.scaled_dot_product_attention.

Step 2: Check off what you can do

Tap each one you can genuinely do or explain. Each earns 10 XP.

Step 3: Go deeper

  • Attention Is All You NeedStart here

    arXiv

    The original architecture: scaled dot-product and multi-head attention, sinusoidal positions and the encoder-decoder layout.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Stanford CS336 Language Modeling from ScratchStart here

    Stanford University

    Section: Assignment 1: Basics (handout and starter code)

    Implement a BPE tokenizer, attention with RoPE, RMSNorm, SwiGLU and a decoder-only language model against unit tests.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Dive into Deep Learning

    d2l.ai (open-source book)

    Section: Ch. 11: Attention Mechanisms and Transformers

    Runnable explanations of attention scoring, multi-head attention, positional encoding and the transformer architecture.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Neural Machine Translation of Rare Words with Subword Units

    arXiv

    The BPE merge algorithm for subword vocabularies that LLM tokenizers build on.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding

    arXiv

    Masked-language-model pretraining and the encoder-only design, as the contrast to next-token prediction.

    Open(opens in a new tab)Link responded, 5 Oct 2026

Step 4: Practice

Start with minbpe: train merges on a small corpus, then compare how your tokenizer and a production tokenizer split numbers, code and non-English text. Next, write multi-head attention with causal and padding masks and test it against torch.nn.functional.scaled_dot_product_attention on random batches with variable lengths, including a fully padded row. For depth, complete the CS336 Assignment 1 components (tokenizer, attention with RoPE, transformer LM, cross-entropy) against its unit tests.

Record attempts on each problem’s page (+15 XP, +10 more when solved on your own).

Step 5: Test yourself

Answer each one out loud or on paper before you finish the lesson.

  1. Question 1What are the shapes of Q, K, V and the attention weights for batch B, h heads, sequence length n and head size d?
  2. Question 2What goes wrong if padded keys are not masked?
  3. Question 3Why does a model with learned absolute positions struggle beyond its training length?
  4. Question 4How does RoPE make attention depend on relative position?
  5. Question 5Why can perplexities not be compared across tokenizers?
  6. Question 6What does the KV cache store, and how does its size scale?
  7. Question 7Why does byte-level BPE never produce unknown tokens?

You’re done when you can

  • Write batched multi-head attention with causal and padding masks from memory, with correct shapes, in under 20 minutes.
  • Explain the sqrt(d_k) scaling, the need for positional information and the causal mask, each in one or two sentences.
  • Train a BPE tokenizer and explain three segmentation quirks it produces.
  • Compare causal and masked language modeling, including which model families use each.

Finish the lesson

How confident do you feel?

Lesson complete!

+50 XP

Reviews will come up on the Practice tab so it sticks.

Unlocks next: Fine-tuning, LoRA, instruction tuning and preference optimization, Retrieval, embeddings and retrieval-augmented generation, Prefill, decode and KV-cache sizing, FlashAttention and IO-aware exact attention, Implementing attention from scratch, AI paper route: Attention, FlashAttention, LoRA, DPO, RAG

Your notes and study time

Log study time