Macalinao StudioLearnAll lessons ↗

TAKE THE LONGER ROUTE

Open the complete college lesson →

Worked explanations, full local narration, and connected Signal Room, Workbench and Field Notes.

SIGNAL ROOM

ArchitecturesUnderstand the moving parts.

Why GPT looks one way, BERT another, T5 a third.

Suggested preparation: None

WORKBENCH / CHANGE ONE THING

Choose who can see whom

Compare bidirectional, causal, and cross-attention connectivity.

Computed teaching example · fixed assumptions shown below

LISTEN & FOLLOW / GUIDED RECAP

Audio starts only when you choose.

FIELD NOTES / THE COMPLETE READING

Take the longer way.

The full lesson narrative, equations and code. Switch views without losing your place.

A slower starting point

Draw arrows between four words and hide the future ones.

Where this deserves more time

Mask shapes; encoder versus decoder objectives; teacher forcing; padding.

Open the complete high-school reading

Moment 01 / 10

Introduction to Transformer Architectures

Welcome. Today we begin our study of Transformer architectures, the foundation of modern large language models. We will cover their origins, the three canonical families, and how these design choices differentiate GPT, BERT, and T5.

Start with the taxonomy: encoder-only, decoder-only, and encoder-decoder architectures. Each imposes a distinct attention pattern and pretraining objective, which in turn determines what the model can and cannot do.

Historically, the original Transformer, Vaswani et al. 2017, was built for machine translation using the encoder-decoder structure. Self-attention replaced recurrence entirely, and that single substitution redefined sequence-to-sequence modeling.

Why do GPT, BERT, and T5 differ architecturally? GPT is decoder-only, trained autoregressively with causal masking for generation. BERT is encoder-only, trained with masked language modeling for bidirectional representation. T5 keeps the full encoder-decoder, casting every task as text-to-text.

We will pair the theory with practical PyTorch implementations. This snippet constructs a single encoder layer, the exact building block stacked twelve deep in BERT-base, with model dimension 512 and eight attention heads.

By the end of this module you will be able to read an architecture diagram, predict its inductive biases, and choose the right family for a given task. Let us begin.

Equations, code and original cards

Introduction to Transformer Architectures

Encoder, Decoder, and Encoder-Decoder Families: Objectives, Masking, Inductive Bias

• Transformer Families (Transformer模型家族): Encoder-only, Decoder-only, Encoder-Decoder

• Historical Context (历史背景): Vaswani et al. 2017, Attention Is All You Need

• Architectural Divergence (架构影响): GPT (causal), BERT (bidirectional), T5 (text-to-text)

• Learning Objectives & Course Structure (学习目标和课程结构)

# PyTorch encoder layer: the BERT building blockencoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8)

Moment 02 / 10

Encoder-Decoder Architecture Design

Encoder-decoder design is the canonical sequence-to-sequence inductive bias: bidirectional encoding of the source, autoregressive decoding, and cross-attention for conditional generation.

The encoder stack uses bidirectional self-attention, so every source position conditions on left and right context, producing contextualized representations rather than a left-to-right prefix summary.

The decoder stack applies causal masking, restricting each target state to previous tokens, then cross-attention reads encoder outputs with decoder queries and encoder keys and values during teacher forcing and inference.

Multi-head attention, from Vaswani and colleagues in twenty seventeen, splits the residual stream into heads that learn distinct query, key, and value projections in parallel.

Scaled dot-product attention forms logits as query times key transpose divided by the square root of the head dimension, then applies softmax over keys and mixes values.

Because attention is permutation invariant, sinusoidal positional encoding adds fixed sine and cosine phases across dimensions, giving the residual stream absolute order without learned parameters.

The PyTorch block implements exactly that: matmul, scale by root head dimension, mask future logits to minus infinity, softmax, then value aggregation, as in T five, BART, and Whisper.

Together, these choices separate understanding from generation while preserving gradient flow through attention, layer normalization, and residuals in modern encoder-decoder systems.

Equations, code and original cards

Encoder-Decoder Architecture: Inductive Bias

Encoder Stack

• Bidirectional Self-Attention

• Source-Contextualized Residual Stream

Decoder Stack

• Causal Masking for Autoregression

• Cross-Attention: Decoder Queries, Encoder Keys/Values

\mathrm{MultiHead}(Q,K,V) = \mathrm{Concat}(\mathrm{head}_1,...,\mathrm{head}_h)W^O \\ \mathrm{head}_i = \mathrm{Attention}(QW_i^Q, KW_i^K, VW_i^V)
\mathrm{Attention}(Q,K,V) = \mathrm{softmax}\left( \frac{QK^{T}}{\sqrt{d_k}} \right)V
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)
# Scaled dot-product attention: logits, mask, softmaxdef scaled_dot_product_attention(Q, K, V, mask=None):  dk = Q.size(-1)  scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(dk)  if mask is not None:    scores = scores.masked_fill(mask == 0, float('-inf'))  attn = torch.softmax(scores, dim=-1)  return torch.matmul(attn, V)

Moment 03 / 10

Encoder-Only Models: BERT and Family

We turn to encoder-only models, exemplified by BERT, Devlin et al. 2019. These models dominated representation learning because bidirectional self-attention builds contextual embeddings that transfer across downstream tasks.

Architecturally, BERT applies fully bidirectional self-attention: every position conditions on both left and right context, with no causal mask. It is purely an encoder, so there is no autoregressive decoder and no cross-attention.

The core pre-training objective is masked language modeling. Roughly fifteen percent of input tokens are selected; of these, eighty percent become mask, ten percent random, ten percent unchanged. The model reconstructs the originals from bidirectional context.

The masked language modeling loss is the negative log likelihood of the true token at each masked position, averaged over those positions: a cross-entropy over the vocabulary, computed only where tokens were hidden.

BERT adds next sentence prediction, a binary classifier on whether segment B follows segment A. Later ablations, notably RoBERTa, showed this objective contributes little and is often dropped.

After fine-tuning, these encoders excel at text classification, named entity recognition, and extractive question answering, where the answer is a span. They also provide strong sentence embeddings for retrieval and semantic similarity.

In summary, encoder-only models such as BERT combine bidirectional self-attention with masked language modeling and sentence-level objectives to learn transferable representations. Understanding this family clarifies the design space that decoder-only models later dominated.

Equations, code and original cards

Encoder-Only Models: BERT and Family (Devlin et al., 2019)

Architecture

• Fully bidirectional self-attention, no causal mask

• Encoder-only: no decoder, no cross-attention

Masked Language Modeling
(MLM) Objective

• Mask ~15% of tokens (80/10/10 mask/random/keep)

• Reconstruct originals from bidirectional context

• Loss: cross-entropy over vocabulary at masked positions only

\mathcal{L}_{MLM} = - \sum_{i \in M} \log P(x_i| \tilde{x})

Next Sentence Prediction (NSP)

• Binary classification: does segment B follow A?

• Weak signal; removed by RoBERTa ablation

Applications

• Text classification and NER sequence labeling

• Extractive QA: answer as an input span

• Sentence embeddings for retrieval and similarity

PyTorch Example: MLM Loss Computation

# Masked Language Modeling losslogits = model(input_ids)loss_fn = nn.CrossEntropyLoss()loss = loss_fn(logits.view(-1, vocab_size), labels.view(-1))

Moment 04 / 10

Decoder-Only Models: GPT Style

Decoder-only models, the GPT lineage from Radford's GPT through GPT-3, are the dominant architecture for large-scale language modeling. Every frontier model you have heard of is, at its core, this design.

The defining mechanism is causal masking: at position t, attention is restricted to positions up to and including t. This enforces the chain-rule factorization of the sequence probability, so each token conditions only on its left context.

Architecturally, this means causal self-attention in every layer, trained with cross-entropy loss under teacher forcing: the model sees gold prefix tokens and is scored on predicting the next token at every position in parallel.

Here is masked attention written out. Scores are Q K transpose over the square root of d-k, and the mask adds negative infinity to every entry above the diagonal, which softmax then maps to exactly zero.

That yields the conditional probability of token x-t given all previous tokens: a softmax over the vocabulary applied to the final hidden state. The training objective is the negative log likelihood, summed over all positions t.

In PyTorch this is a few lines: build a lower-triangular mask with torch.tril, compute scaled dot-product scores, fill the masked entries with negative infinity, and apply softmax along the last dimension.

Without masking, the model would trivially copy future tokens and the loss would collapse to zero while learning nothing. Causal masking is what makes next-token prediction a genuine learning problem.

To summarize: decoder-only models combine causal self-attention with a next-token cross-entropy objective under teacher forcing. This simple recipe, scaled to trillions of tokens, is the backbone of every modern large language model.

Equations, code and original cards

Decoder-Only Models: GPT Style

Causal masking, autoregressive factorization, and next-token prediction

• Architecture: causal self-attention over the residual stream
• Loss: cross-entropy with teacher forcing, L = −Σ_t log p(x_t | x_<t)
• Key applications: GPT series, LLaMA, PaLM

\text{Masked Attention: }\\ \text{Softmax}\left( \frac{QK^{\top}}{\sqrt{d}} + M \right) V
P(x_t | x_{<t}) = \text{Softmax}(W_o h_t)
# Causal masked self-attention in PyTorchmask = torch.tril(torch.ones(seq_len, seq_len)) == 1scores = (Q @ K.transpose(-2, -1)) / math.sqrt(d_k)scores = scores.masked_fill(~mask, float('-inf'))attn = torch.softmax(scores, dim=-1)

• Causal masking zeroes attention to future positions via −inf logits

• Teacher forcing trains all positions in parallel with cross-entropy

• Factorizes p(x) as a product of next-token conditionals, enabling autoregressive sampling

Moment 05 / 10

Interactive Architecture Comparison

Start with the Encoder Attention node. It applies bidirectional self-attention: with no causal mask, every query attends to every key, so the effective receptive field spans the full sequence. Watch how that unrestricted context reshapes each token's residual stream.

Now move to Decoder Attention. A causal mask zeroes out all future positions, so the distribution at position t conditions only on tokens up to t, enforcing the autoregressive factorization.

Next, the Encoder-Decoder Cross-Attention node. Here queries come from the decoder residual stream while keys and values come from the encoder output, so each decoder step reads the entire source representation.

Now sweep the layer count and track how representations evolve through the residual stream. Contrast the bidirectional encoder's global mixing against the decoder's left-to-right bottleneck, and note the cost: attention scales quadratically in sequence length.

Equations, code and original cards

Moment 06 / 10

Advanced Techniques and Optimizations (2024-2026)

Welcome back. This segment examines advanced transformer techniques from 2024 through 2026, emphasizing how recent architectural and systems-level innovations improve computational efficiency and scalability at frontier scale.

We begin with efficient attention variants: sparse attention, linearized kernel methods, and low-rank projections. Each attacks the quadratic complexity of standard softmax attention, whose cost grows as n-squared times d in sequence length and hidden dimension.

Scaling laws then quantify how loss depends on parameter count, dataset tokens, and compute. Kaplan and colleagues established these power laws; Hoffmann's Chinchilla analysis showed compute-optimal training requires roughly twenty tokens per parameter.

For training at scale, gradient checkpointing and mixed precision are essential. Checkpointing trades recomputation for activation memory, while b-f-16 mixed precision roughly halves memory and accelerates throughput with negligible degradation in final accuracy.

Moving from theory to implementation, these PyTorch snippets realize efficient attention in practice, demonstrating how sparse masking integrates into a real attention block without altering the surrounding architecture.

Here is a sparse attention mask in PyTorch: a boolean tensor that zeroes out disallowed query-key pairs before the softmax, cutting both FLOPs and memory while preserving the chosen sparsity pattern.

Together, these techniques define the current frontier of transformer engineering, enabling longer contexts and larger models under fixed compute budgets. Carry them forward as we turn to more complex applications.

Equations, code and original cards

Advanced Techniques and Optimizations (2024-2026)

Efficient Attention Variants

• Sparse Attention (block/local sparsity patterns)
• Linearized Attention (kernel feature maps)
• Low-Rank Projections (compressed key-value matrices)

Scaling Laws

• Parameter scaling (Kaplan et al. 2020)
• Token scaling (Chinchilla: N ~ 20D)
• Compute-optimal trade-offs
(参数 parameters, 数据 tokens, 算力 compute)

Training Optimizations

• Gradient Checkpointing (recompute vs. store)
• Mixed Precision (b-f-16: halved memory)
(梯度检查点, 混合精度训练)

PyTorch Efficient Attention Snippets

• Sparse mask construction
• Kernel-based linear attention
• b-f-16 autocast setup

# Sparse attention mask: boolean mask applied pre-softmax

Moment 07 / 10

Mathematical Derivations and Whiteboard Formulas

Today we derive the gradients underlying transformer training, specifically backpropagation through scaled dot-product attention as defined in Vaswani et al. 2017. The whiteboard holds the key formulas; we begin with an overview.

First, the gradient of scaled dot-product attention, the core operation of the architecture. This Jacobian governs how the model assigns credit during learning, and understanding it is essential for reasoning about optimization dynamics.

Here is the forward computation: softmax of Q K transpose over the square root of d-k, applied to V. We trace each matrix multiplication so you can see how the residual stream transforms during the forward pass.

Next, the partial derivative of the loss with respect to the attention inputs. This matrix calculus expresses how gradients flow backward through the softmax and the bilinear score function.

This segment derives the transformer gradient formulas using matrix calculus. We expand the Jacobian of the softmax and the chain rule through the Q K transpose product to clarify backpropagation through multi-head attention.

To connect theory to implementation, here is a PyTorch snippet computing the gradient for scaled dot-product attention. We walk through the autograd calls line-by-line to map them to the mathematical derivations.

In summary, we have derived the gradients for scaled dot-product attention, which drive gradient-based updates in transformer training. This foundation applies whether you are pretraining with masked language modeling or autoregressive next-token prediction.

Clarification: Attention backprop requires the softmax Jacobian and multiplication by K.

Equations, code and original cards

Mathematical Derivations and Whiteboard Formulas

Key Transformer Gradient Formulas & Matrix Calculus

Topics Covered:

• Gradient of scaled dot-product attention

• Backpropagation through multi-head attention layers

• Loss gradients: MLM & autoregressive

• Stepwise matrix calculus derivations

\text{Attention}(Q,K,V) = \text{softmax}\left(\frac{QK^{\top}}{\sqrt{d}}\right) V
G_A=G_OV^\top;\quad G_S=A\odot(G_A-\operatorname{rowsum}(A\odot G_A));\quad G_Q=G_SK/\sqrt{d_k}
# PyTorch snippet: Gradient of scaled dot-product attentionscore = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)weights = torch.softmax(score, dim=-1)grad_output = torch.autograd.grad(outputs=loss, inputs=weights)grad_Q = torch.matmul(grad_output, V.transpose(-2, -1)) / math.sqrt(d_k)

Moment 08 / 10

Implementation Details with Python/PyTorch

We now implement transformer blocks in PyTorch: tensor shapes, projections, masking, normalization. The objective is modular, fused, memory-aware code that maps cleanly onto Vaswani et al.'s equations.

The roadmap is the residual stream: multi-head self-attention, position-wise feed-forward networks, causal and padding masks, then positional information injected before the first block.

Start with the layer primitives. Multi-head attention mixes token states through learned query, key, value projections; the position-wise MLP then expands each state to four times d-model and projects back.

The class splits d-model into heads, computes query key transpose scores scaled by the square root of d-head, masks invalid logits to minus infinity, applies softmax, contracts with values, then reprojects the concatenated heads.

Masks are boolean constraints on logits. Encoder padding masks hide pad tokens; decoder causal masks enforce lower-triangular visibility for teacher forcing; cross-attention masks decoder queries against encoder padding, preserving autoregressive information flow.

Because attention is permutation equivariant, order must enter through the residual stream: add sinusoidal encodings to embeddings, or apply rotary position embeddings to queries and keys so relative offsets shape the logits.

Composed as modules, these pieces yield an auditable residual stack: attention sublayer, MLP sublayer, normalization, dropout, masks. The same idioms scale from a toy encoder to FlashAttention-style kernels and distributed training.

Equations, code and original cards

Transformer Implementation in PyTorch: From Equations to Kernels

Residual-stream components: projections, masks, normalization, positional signal

• Multi-head attention: QKV projections, scaled logits, head split/merge

• Masks: encoder padding, decoder causal, cross-attention key padding

• Position: sinusoidal injection or RoPE rotation of queries/keys

• Code: shape discipline, finite masking, dropout, residual adds

# Multi-head self-attention: logits = Q K^T / sqrt(d_head)
class MultiHeadAttention(nn.Module):
    def __init__(self, d_model, num_heads, dropout=0.0):
        super().__init__()
        assert d_model % num_heads == 0
        self.num_heads = num_heads
        self.d_head = d_model // num_heads

        self.q_linear = nn.Linear(d_model, d_model)
        self.k_linear = nn.Linear(d_model, d_model)
        self.v_linear = nn.Linear(d_model, d_model)
        self.out_linear = nn.Linear(d_model, d_model)
        self.attn_dropout = nn.Dropout(dropout)

    def forward(self, q, k, v, mask=None):
        batch_size = q.size(0)

        # Project, then split d_model into independent heads
        Q = self.q_linear(q).view(batch_size, -1, self.num_heads, self.d_head).transpose(1, 2)
        K = self.k_linear(k).view(batch_size, -1, self.num_heads, self.d_head).transpose(1, 2)
        V = self.v_linear(v).view(batch_size, -1, self.num_heads, self.d_head).transpose(1, 2)

        # Scaled dot-product logits; mask before softmax
        scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_head)
        if mask is not None:
            scores = scores.masked_fill(mask == 0, torch.finfo(scores.dtype).min)

        attn = self.attn_dropout(torch.softmax(scores, dim=-1))
        output = torch.matmul(attn, V)

        # Merge heads and reproject into the residual stream
        output = output.transpose(1, 2).contiguous().view(batch_size, -1, self.num_heads * self.d_head)
        return self.out_linear(output)

Moment 09 / 10

Cutting-Edge Variations and Open Research Questions

Let's survey the frontier of transformer architecture variants and the open research questions that currently drive the field.

First, encoder-decoder hybrids and conditional computation are gaining traction. Mixture-of-experts layers route each token to a sparse subset of feed-forward networks, decoupling parameter count from per-token compute.

Next, alignment: reinforcement learning from human feedback, as in Ouyang et al.'s InstructGPT, and Rafailov et al.'s direct preference optimization, which fits the reward signal implicitly through a closed-form classification objective.

Research trends also point toward multimodal transformers that embed text, images, and audio into a shared token stream, and toward sparse expert models whose routing yields large capacity at fixed inference cost.

Finally, open questions: do the Kaplan and Chinchilla scaling laws extend to sparse and multimodal regimes, how far can efficiency be pushed beyond FlashAttention, and what governs out-of-distribution generalization?

Together, these directions mark both the field's rapid progress and its unresolved challenges, setting an active agenda for your own research.

Equations, code and original cards

Cutting-Edge Variants and Open Research Questions

• Encoder–decoder hybrids: T5, UL2, dynamic depth

• Conditional computation: Mixture-of-Experts routing

• Alignment: RLHF (Ouyang et al. 2022), DPO (Rafailov et al. 2023)

• Bias mitigation, safety, interpretability

• Multimodal transformers: unified token streams (多模态变换器)

• Sparse expert models: Switch, GLaM (稀疏专家模型)

• Do Chinchilla scaling laws hold for MoE and multimodal?

• Efficiency beyond FlashAttention; OOD generalization

Moment 10 / 10

Comprehensive Quiz: Concepts and Computations

Now let's test how deeply the material has settled: architecture families, attention variants, scaling laws, and the computations behind them. Attempt every question before checking the answer.

When you've completed the quiz, we'll walk through the results together, diagnose any errors, and sharpen the concepts that need it.

Equations, code and original cards

MAKE IT YOURS

Explain the change.

References, scope & corrections

Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.

1 correction entries · expansion notes

Reset this lesson?

This removes only this lesson’s saved notes, experiments and progress.