Decoder Layer, Cross-Attention, and Teacher Forcing
2682 words
13 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Decoder Layer, Cross-Attention, and Teacher Forcing ## 🎯 Learning Objectives - Explain the three sublayers in the Transformer decoder - Distinguish between masked self-attention and cross-attention - Understand teacher forcing and its role in training - Implement causal masking for autoregressive generation - Com...

Decoder Layer, Cross-Attention, and Teacher Forcing
🎯 Learning Objectives
- Explain the three sublayers in the Transformer decoder
- Distinguish between masked self-attention and cross-attention
- Understand teacher forcing and its role in training
- Implement causal masking for autoregressive generation
- Compare training-time vs inference-time decoding
📋 Prerequisites
- Transformer architecture (Week 1)
- Self-attention and QKV computation
- Multi-head attention
1. 📖 Core Content
1.1 Decoder Architecture
The Transformer decoder has three sublayers (not two like the encoder):
(Diagram)
| Sublayer | Purpose | Q Source | K/V Source | Mask? |
|---|---|---|---|---|
| Masked Self-Attention | Process generated tokens | Decoder | Decoder | Yes (causal) |
| Cross-Attention | Look at input | Decoder | Encoder | No |
| Feed-Forward | Non-linear transform | - | - | - |
1.2 Masked Self-Attention
Intuition
When generating text, the model should only see words it has already generated — not future words. If you're generating "The cat sat," when predicting "sat," you should only know "The" and "cat."
Masked self-attention enforces this by setting attention scores for future positions to −∞ before softmax.
Implementation
MaskedAttention(Q,K,V)=softmax(dkQKT+M)VWhere M is a causal mask:
0 & \text{if } i \geq j \text{ (allowed)} \\ -\infty & \text{if } i < j \text{ (masked)} \end{cases}
S = \begin{bmatrix} 2.0 & 0.5 & 1.0 & 0.1 \\ 0.3 & 1.5 & 0.8 & 2.0 \\ 1.2 & 0.7 & 1.8 & 0.4 \\ 0.9 & 1.1 & 0.6 & 1.4 \end{bmatrix}
M = \begin{bmatrix} 0 & -\infty & -\infty & -\infty \\ 0 & 0 & -\infty & -\infty \\ 0 & 0 & 0 & -\infty \\ 0 & 0 & 0 & 0 \end{bmatrix}
S + M = \begin{bmatrix} 2.0 & -\infty & -\infty & -\infty \\ 0.3 & 1.5 & -\infty & -\infty \\ 1.2 & 0.7 & 1.8 & -\infty \\ 0.9 & 1.1 & 0.6 & 1.4 \end{bmatrix}
Decoder input so far (3 tokens, d_model=4):
M_{ij} = \begin{cases} > 0 & \text{if } j \leq k \text{ or } i \geq j \\ > -\infty & \text{otherwise} > \end{cases}
x_{out} = x_{in} + \text{Sublayer}(x_{in})
\frac{\partial L}{\partial x_{in}} = \frac{\partial L}{\partial x_{out}} \cdot \frac{\partial x_{out}}{\partial x_{in}} = \frac{\partial L}{\partial x_{out}} \cdot \left(1 + \frac{\partial \text{Sublayer}}{\partial x_{in}}\right)$$ > > The "1" term ensures gradients can flow directly through the residual path without vanishing, even if fracpartialtextSublayerpartialxin is small. This is crucial for training deep (12+ layer) decoders. > Q7: In teacher forcing, the decoder processes all positions in parallel. How does this work with causal masking? > > The decoder computes attention for all positions simultaneously using matrix operations. The causal mask ensures that position i only attends to positions j ≤ i, even though all positions are processed at once. > > Conceptually: it's as if we run the decoder step-by-step, but the mask makes the parallel computation equivalent to the sequential one. The only difference is training efficiency — parallel is much faster. > Q8: Why does the decoder have 3 add-and-norm layers while the encoder has only 2? > > The decoder has an additional sublayer (cross-attention) compared to the encoder. Each sublayer is wrapped with a residual connection and layer normalization. So: > - Encoder: 2 sublayers (self-attention + FFN) → 2 add-and-norm > - Decoder: 3 sublayers (masked self-attention + cross-attention + FFN) → 3 add-and-norm > Q9: How would you implement scheduled sampling (mixing ground truth and predictions) in a decoder? > > At each training step with probability ε (which decays over time): > - Use model's predicted token as input (instead of ground truth) > - Otherwise use ground truth (standard teacher forcing) > > ```python > def scheduled_sampling_decoder_step(decoder, prev_token, encoder_output, epsilon): > """Mix ground truth and predictions""" > if np.random.random() < epsilon: > # Use model's prediction > logits = decoder(prev_token, encoder_output) > predicted_token = np.argmax(logits) > return predicted_token > else: > # Use ground truth (teacher forcing) > return ground_truth_token > ``` > > Schedule: ε starts high (e.g., 0.5) and decays to 0 during training. > Q10: In a 6-layer decoder, how many total attention mechanisms process each token during generation? > > Each decoder layer has 2 attention mechanisms (masked self-attention + cross-attention). With 6 layers: > Total = 6 × 2 = 12 attention mechanisms per token > > But during inference, previously computed attention values (keys and values) can be cached (KV-cache), so each new token only needs to compute attention with the new key-value pairs. This makes inference O(n) per token instead of O(n²). --- ## 7. 🔗 Cross-References - Next: [Layer Normalization & Residual Connections](/courses/bsda5004/notes/06-layer-norm-residual) - Advanced: KV-Cache Optimization (Week 10) - Video: BSDA5004 Week 2-3 transcripts
Join Discord
PreviousPositional EncodingNextLayer Norm & Residual