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

Encoder-DecoderUnderstand the moving parts.

A return to the encoder-decoder pattern.

Suggested preparation: 07, 12

WORKBENCH / CHANGE ONE THING

Read a different sequence

Change a decoder query while the source sequence remains fixed.

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

Ask one question of three source notes and combine their answers.

Where this deserves more time

Separate source and target lengths; causal self-attention versus cross-attention.

Open the complete high-school reading

Moment 01 / 10

Course Introduction and Overview

Welcome to the course on encoder-decoder architectures: the framework behind modern sequence transduction, from neural machine translation to speech recognition.

At its core, an encoder maps a variable-length input into contextual hidden states, while a decoder factors the output distribution autoregressively, token by token, often with cross-attention to those states.

We will study the residual stream, attention as content-based routing, causal masking, teacher forcing, and the inductive biases that make translation, summarization, and captioning tractable.

Our goals are explicit: derive the training objective, analyze gradient flow and normalization choices, and implement systems whose failure modes you can diagnose rather than merely observe.

Topics move from probabilistic foundations and maximum likelihood to beam search, subword tokenization, efficient attention, ablation methodology, and current work on long-context and multimodal decoding.

By the end, you should be able to specify an encoder-decoder model, justify its objective and architecture, train it reproducibly, and critique it with quantitative evidence.

Equations, code and original cards

Encoder-Decoder Architectures: Course Overview

• Define encoder-decoder models as conditional sequence transducers

• Goals: objectives, optimization, implementation, reproducible evaluation

• Topics: probabilistic foundations, attention, decoding, ablations, research frontiers

Moment 02 / 10

Encoder vs Decoder: Functional Roles

We now contrast encoders and decoders at the level of their attention topology, the structural choice that dictates each architecture's functional role.

The encoder's defining property is bidirectional attention: every position attends to the full input sequence, so each representation is conditioned on both left and right context.

BERT, introduced by Devlin and colleagues in 2019, exploits this to build deep contextual embeddings, pretrained with masked language modeling rather than left-to-right prediction.

The decoder instead applies causal masking: each position attends only to itself and earlier positions, enforcing the autoregressive factorization of the sequence likelihood.

GPT trains exactly this objective, minimizing the negative log likelihood of each token given its prefix, which makes generation a sequential sampling procedure.

The summary: encoders are inspectors, building rich bidirectional representations for understanding; decoders are generators, sampling continuations under a causal mask.

Equations, code and original cards

Encoder vs Decoder: Functional Roles

Encoder

Decoder

• Bidirectional attention over full input

• BERT (Devlin et al., 2019): masked-LM pretraining

• Inspectors: contextual representations

• Causal masked attention, autoregressive

• GPT: next-token negative log-likelihood

• Storytellers: sequential generation

Moment 03 / 10

Mathematical Foundations: Matrix Operations

We start with the linear algebra underneath encoder-decoder networks: token embeddings form a residual stream, and every block is a differentiable map on matrices. The operations here are the vocabulary for attention.

Each token id is mapped to a d-dimensional embedding; a sequence becomes a matrix whose rows are those vectors. Batching stacks sequences so kernels run as dense matrix multiplies.

We write the input as an n by d matrix: n positions, d channels. Each row mixes learned semantics with positional encoding, since attention itself is permutation invariant.

The block returns another n by d matrix, added back to the residual stream. Shapes are the contract: constant width lets layers compose without projection bookkeeping.

Attention begins with three learned linear maps from the same residual stream into queries, keys, and values. This is an inductive bias: compare content with content, then route value vectors accordingly.

Concretely, the input matrix is right-multiplied by three learned weight matrices to yield the query, key, and value matrices; their inner products will score pairwise token affinity.

The core operation is scaled dot-product attention from Vaswani and colleagues in 2017: queries meet keys by inner product, and scale controls the softmax temperature.

It forms query times key transpose, divides by the square root of the key dimension to keep logits unit-scale, applies row-wise softmax, then mixes the value rows into context vectors.

Together these maps make content-dependent routing: attention weights are computed per pair, cost grows quadratically in sequence length, and causal masking enforces the negative log likelihood objective for next-token prediction.

Equations, code and original cards

Linear Algebra of Encoder-Decoder Attention

Token Embeddings
Sequence as n by d Matrix
Residual Stream Width d

Scaled Dot-Product
Attention: Logits to Weights

Learned Projections:
Queries, Keys, Values
Shared Residual Input

\text{Input tokens: } X = [x_1, \ x_2, \ \dots, \ x_n]\in \mathbb{R}^{n \times d}
\text{Output tokens: } Y = [y_1, \ y_2, \ \dots, \ y_m] \in \mathbb{R}^{m \times d}
\mathrm{Attention}(Q,K,V) = \mathrm{softmax}\left( \frac{Q K^\top}{\sqrt{d_k}} \right) V
Q = X W_Q, \quad K = X W_K, \quad V = X W_V

Moment 04 / 10

Gradient Derivations and Backpropagation

Today we derive the gradients that drive backpropagation through attention, tracing how the loss signal propagates through the softmax, the value projections, and ultimately updates every parameter in the encoder-decoder stack.

Begin with the chain rule applied to attention. Attention is a composition: softmax of the query-key score matrix scaled by the square root of d-k, multiplied by the value matrix. Gradients therefore factorize into products of local Jacobians.

Consider the partial derivative of the loss with respect to the query matrix. It flows backward through the softmax Jacobian and the attention scores, and its magnitude tells us precisely how sensitive the loss is to each query vector.

Next, gradient flow through multi-head attention. Each head is an independent path, so the gradient arriving at the concatenated output splits across heads, and the total gradient at the input is the sum over all heads' contributions.

This PyTorch snippet shows the backward pass in practice: calling backward on the attention weights accumulates gradients into the grad attribute of the query, key, and value tensors.

Finally, loss gradients and parameter updates. Under cross-entropy, the gradient at the logits is the softmax probability vector minus the one-hot target; Adam then rescales this signal with running first and second moment estimates before each step.

To summarize: the chain rule decomposes attention gradients into local Jacobians, the multi-head structure sums contributions across parallel heads, and the optimizer rescales these gradients to drive every parameter update in the encoder-decoder network.

Equations, code and original cards

Gradient Derivations and Backpropagation Through Attention

• Chain rule through softmax and score Jacobians

• Gradient summation across parallel attention heads

• Cross-entropy gradients and optimizer updates

Chain Rule Through Attention

\frac{\partial L}{\partial Q} = \frac{\partial L}{\partial Z} \cdot \frac{\partial Z}{\partial Q}

Gradient Flow Across Parallel Heads

# Backward pass through attention weightsattn_weights.backward(grad_output)grads = { 'Q': Q.grad, 'K': K.grad, 'V': V.grad }

Cross-Entropy Gradients and Parameter Updates

Moment 05 / 10

Interactive Visualization: Attention Mechanisms

Attention is a differentiable routing mechanism over the residual stream. The Input Sequence node holds token embeddings, rows of the learned embedding matrix.

Bidirectional encoder attention applies no causal mask: every query attends to the full key set, so each position's effective receptive field spans the entire sequence, as in BERT.

Autoregressive decoder attention applies a causal mask, zeroing attention weights to future positions, so each token's distribution depends only on its prefix, enabling teacher forcing.

Use the Masking slider to push masked logits toward negative infinity before the softmax; watch the decoder's attention entropy concentrate onto the permitted prefix.

Change the Sequence Length slider and note the cost: the pairwise score matrix grows quadratically, so attention compute scales as n squared times d.

The final outputs node writes consolidated encoder and decoder contexts into the residual stream, feeding layer normalization and the feed-forward block.

Equations, code and original cards

Moment 06 / 10

Implementation Details: Python/PyTorch Code

Now we translate the encoder-decoder architecture of Vaswani et al. 2017 into concrete PyTorch modules.

These class definitions modularize the architecture: each encoder layer encapsulates multi-head self-attention and a position-wise feed-forward network, each wrapped in residual connections and layer normalization; the decoder adds a cross-attention sublayer over the encoder's output.

This snippet is scaled dot-product attention: scores are query times key transpose, divided by the square root of d-k to keep the softmax out of its saturated regime, then normalized and contracted with the value tensor.

Finally, the training loop: token-level cross-entropy against the ground-truth targets, backpropagation through the full computation graph, and an optimizer step, typically Adam with the warmup-and-decay schedule from the original paper.

To summarize: modular encoder and decoder layers, attention as three tensor contractions with a scaled softmax, and a standard teacher-forced cross-entropy training loop.

These building blocks are not incidental; the residual stream and normalization placement are precisely what make deep stacks trainable at scale.

Equations, code and original cards

Implementation Details: Python/PyTorch Code

Key Components Overview

# Encoder and Decoder Layersclass EncoderLayer(nn.Module):
   def __init__(self, ...):
     super().__init__()
     # multi-head self-attn, FFN, residual + LayerNormclass DecoderLayer(nn.Module):
   def __init__(self, ...):
     super().__init__()
     # masked self-attn, cross-attn, FFN
# Scaled Dot-Product Attentionscores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
attn = torch.softmax(scores, dim=-1)
output = torch.matmul(attn, value)
# Cross-Entropy Loss and Training Looploss = criterion(predictions, targets)
loss.backward()
optimizer.step()
optimizer.zero_grad()

Moment 07 / 10

State-of-the-Art Techniques and Optimizations (2024-2026)

Let's survey the techniques defining frontier model development from 2024 through 2026: compute-optimal scaling, sub-quadratic attention, and post-training alignment. These are the levers that determine capability per dollar at the ten-to-the-twenty-five-FLOP scale.

First, efficient attention variants attack the quadratic cost of standard self-attention. FlashAttention tiles the softmax computation to saturate GPU memory bandwidth, while multi-query and grouped-query attention shrink the key-value cache. Sparse and sliding-window patterns reduce complexity toward linear in sequence length.

Second, scaling laws let us predict loss as a power law in parameters, data, and compute. Chinchilla established that tokens and parameters should grow together, roughly twenty tokens per parameter. Modern work extends this to data-constrained regimes and mixture-of-experts, where only a fraction of parameters activate per token.

Third, alignment and robustness techniques make models behave reliably under deployment. RLHF and direct preference optimization shape the policy toward human preferences, while constitutional methods and adversarial red-teaming probe failure modes. Without this post-training stage, a capable base model is not a deployable system.

Together, these threads define the current frontier: compute-optimal pretraining, memory-efficient attention, and principled alignment. Keep these themes in mind as we examine each mechanism in detail.

Equations, code and original cards

State-of-the-Art Techniques and Optimizations (2024-2026)

Compute-optimal scaling, sub-quadratic attention, and post-training alignment

FlashAttention, MQA/GQA, Sparse & Sliding-Window Attention

Chinchilla Scaling Laws & Mixture-of-Experts

RLHF, DPO, and Adversarial Robustness

Moment 08 / 10

Advanced Variations and Open Research Questions

We now turn to advanced encoder decoder variants and the open problems that currently constrain sequence to sequence modeling, from alignment to grounded generation.

One direction couples a frozen pretrained encoder or decoder with low rank adapters or instruction tuned heads, trading full fine tuning for parameter efficient transfer.

A second direction augments the decoder with retrieval over an external index and with multimodal encoders, so conditioning can include text, image tokens, audio features, or structured evidence.

The hard questions are attribution and robustness: which retrieved span caused the logit shift, and does the model fail gracefully under distribution shift rather than hallucinating confidently.

Progress will come from ablations that isolate inductive bias, better uncertainty estimates, and evaluations that measure faithfulness, calibration, and sample complexity instead of benchmark accuracy alone.

Equations, code and original cards

Advanced Variants and Open Problems

• Parameter efficient hybrids: frozen backbones plus low rank adapters, prefixes, or instruction tuned heads

• Retrieval augmented and multimodal conditioning across text, image, audio, and structured evidence

• Interpretability: faithfulness of rationales, attribution to retrieved spans, calibrated uncertainty

• Generalization: robustness to distribution shift, domain transfer, contamination, and long context

Moment 09 / 10

Challenging Quiz: Concepts and Computations

Time to stress-test the encoder-decoder material: cross-attention, causal masking, teacher forcing, and the sequence-level negative log likelihood. Work every problem on your own before looking at any solution.

Submit your answers, then we'll walk through the errors, the gradient flow, and any step where the computation broke down.

Equations, code and original cards

Moment 10 / 10

Summary and Next Steps

We close by consolidating the encoder-decoder framework, then map concrete next steps for deeper study.

First, we revisit the residual stream, attention logits, causal masking, and the cross-entropy objective underlying sequence-to-sequence learning.

Notice how the scaled dot product, softmax normalization, and layer normalization jointly determine gradient norm and optimization stability.

Next, we survey FlashAttention, grouped-query attention, retrieval augmentation, mixture-of-experts routing, and direct preference optimization, with open problems in long-context evaluation.

These directions are not decorative; they determine sample complexity, latency, effective receptive field, and credible ablation design for your projects.

Finally, read Vaswani and colleagues on attention, Ouyang and colleagues on instruction tuning, and Rafailov and colleagues on preference optimization.

Take time to reproduce a small encoder-decoder, inspect attention maps, measure cross-entropy and Kullback Leibler divergence, and connect failures to inductive bias rather than folklore.

With these mechanisms and references in hand, you can interrogate encoder-decoder systems rigorously and extend them with disciplined experiments.

Equations, code and original cards

Encoder-Decoder Summary and Next Steps

• Mechanisms: residual stream, attention logits, causal masking, cross-entropy

• Frontiers: FlashAttention, grouped-query attention, retrieval, mixture-of-experts, DPO

• Practice: reproduce, ablate, inspect attention, report calibration and latency

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.

0 correction entries · expansion notes

Reset this lesson?

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