Encoders, Decoders, and Cross-Attention

Dive into Deep Learning · §11.4

Bidirectional Encoders, Encoder–Decoders, and Cross-Attention
three block wirings · masked language modeling · sequence-to-sequence cross-attention · Perceiver latent bottlenecks

Why Causal Masking Hurts When Full Input Is Known

Motivation

  • Cloze disambiguation: In Homarus gammarus, known as _he European lobster, the left prefix known as permits hundreds of completions, whereas the right context he European uniquely pins the missing byte to t (96\text{--}97\% probability).
  • Two-sided context gain: On WikiText-103 byte windows, reconstructing a masked byte drops from \sim 2.4\text{ nats} at the 1-sided window boundary to \approx 1.55\text{ nats} in the 2-sided interior.

One Transformer Block, Three Canonical Wirings

Architectural Taxonomy

  • 1. Encoder-only (is_causal=False): Every token attends to every token across all L layers in a single bidirectional pass (BERT, RoBERTa, ViT).
  • 2. Decoder-only (is_causal=True): Each token attends only to positions j \le i, handling prompt reading and generation in one homogeneous stack (GPT, Llama 3, Qwen3).
  • 3. Encoder–decoder: A bidirectional encoder maps source \mathbf{X}_{\text{src}} \to \mathbf{H}_{\text{enc}}, and a causal decoder generates \mathbf{Y}_{\text{tgt}} while reading \mathbf{H}_{\text{enc}} via cross-attention (2017 Transformer, T5, Whisper).
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

A Bidirectional Encoder Drops the Causal Mask

Encoder Implementation

Removing the triangular mask from d2l.TransformerBlock turns a causal stack into TransformerEncoder, mapping an (B, n) batch of token IDs to bidirectional contextual representations in \mathbb{R}^{B \times n \times d}:

def forward(self, X, mask=None):          # X: (batch, n) token ids
    H = self.token_emb(X) + self.pos_emb(
        torch.arange(X.shape[1], device=X.device))
    for blk in self.blks:                 # Pre-norm d2l.TransformerBlock stack
        H = blk(H, mask)                  # mask=None -> all tokens attend to all
    return self.norm(H)                   # (batch, n, d) bidirectional embeddings

Every output vector \mathbf{h}_i^{(L)} \in \mathbb{R}^d summarizes the entire sequence from position i’s vantage point; pooling across positions (mean pooling or reading index 0) produces a single fixed-width embedding per document.

Pitfall: Why Encoders Cannot Train on Next-Token Loss

Information Leakage Hazard

  • Layer 1 direct leakage: Query t attends directly to key t+1, copying target embedding \mathbf{e}_{x_{t+1}} into \mathbf{h}_t^{(1)}.
  • Layer 2 multi-hop leakage: Even if (t, t+1) were masked, query t at layer 2 attends to position t+2 (or t-1), which already read x_{t+1} in layer 1.
  • Rule: Any target token x_i (i \in \mathcal{M}) must be replaced by <mask> in the input before layer 1.

Masked Language Modeling (MLM)

Bidirectional Pretraining

Introduced in BERT (Devlin et al., 2018), Masked Language Modeling samples a random subset of positions \mathcal{M} \subset \{1, \dots, n\} (with probability p = 0.15), replaces each x_i (i \in \mathcal{M}) with a dedicated <mask> token ID in \tilde{\mathbf{x}}, and scores cross-entropy only on the masked subset \mathcal{M}:

\mathcal{L}_{\mathrm{MLM}}(\boldsymbol{\theta}) = -\frac{1}{|\mathcal{M}|} \sum_{i \in \mathcal{M}} \log P_{\boldsymbol{\theta}}(x_i \mid \tilde{\mathbf{x}})

masked loss at step 500/1000/2000: 3.12/2.28/1.60
  • Label masking (-100): Unmasked positions (i \notin \mathcal{M}, 85\% of tokens) receive target label -100 so they contribute context without adding trivial copy terms to the loss.
  • Sample efficiency trade-off: Each training window supervises only 15\% of its tokens (around 10 bytes out of 64), compared to 100\% of tokens in a causal GPT.

The U-Shaped Loss Curve Across Window Positions

Value of Two-Sided Context

Evaluating our trained 4-block byte-level MaskedLM across window positions t \in \{0, \dots, 63\} contrasts sharply with a causal model’s monotonically decreasing curve:

masked accuracy 0.53
loss at positions 0-3: 2.36 1.78 1.54 1.52; 60-63: 1.56 1.56 1.76 2.37; interior mean 1.54
  • Symmetric bathtub (U-shaped) profile: Interior positions (t \in [16, 47]) enjoy both left and right context, achieving a flat mean loss of \approx 1.55\text{ nats/byte} (\approx 53\% exact byte accuracy).
  • Edge penalty at t = 0 and t = 63: At the two window boundaries where one side of the context is truncated, loss jumps to 2.36\text{--}2.44\text{ nats/byte}—quantifying the \sim 0.85\text{-nat} advantage of having the second side of context.

How Right-Hand Context Resolves Ambiguous Gaps

Qualitative Probing

  • Masking individual bytes in 'Homarus gammarus , known as the European lobster' shows how bidirectional attention fuses left and right spelling constraints:
  • At position 28 (known as _he European), the encoder assigns 96\text{--}97\% probability to 't'; at position 22 (kno_n as), it assigns 47\text{--}66\% to 'w'.

How Right-Hand Context Resolves Ambiguous Gaps (cont.)

Qualitative Probing

The probe masks one byte at a time and prints the encoder’s top three guesses for it:

snippet = 'Homarus gammarus , known as the European lobster or common '
ids = torch.tensor(data.vocab.encode(snippet), device=device)[None]
for pos in (11, 22, 28):
    Xm = ids.clone()
    Xm[0, pos] = MASK
    with torch.no_grad():
        logits = model(Xm)
    probs = F.softmax(logits[0, pos], -1)
    top = probs.topk(3)
    shown = snippet[:pos] + '_' + snippet[pos + 1:]
    print(f'{shown[:40]!r}... -> '
          + ', '.join(f'{data.vocab.decode([int(i)])!r} {p:.2f}'
                      for p, i in zip(top.values, top.indices)))
'Homarus gam_arus , known as the European'... -> 'p' 0.44, 'b' 0.17, ' ' 0.12
'Homarus gammarus , kno_n as the European'... -> 'w' 0.47, 'i' 0.24, 'o' 0.10
'Homarus gammarus , known as _he European'... -> 't' 0.96, 'T' 0.02, 's' 0.01

Sequence-to-Sequence Alignment: String Reversal

Encoder–Decoder Benchmark

  • Teacher-forced decoder input (dec_in): Prepends <bos> (id = 16) and shifts the reversed target right by one slot: dec_in = (\texttt{<bos>}, x_T, \dots, x_2) predicts tgt = (x_T, \dots, x_1).
  • Exact ground-truth alignment: To emit target position t, the decoder must retrieve source token x_{T - 1 - t} along the anti-diagonal (t, T - 1 - t).

Sequence-to-Sequence Alignment: String Reversal (cont.)

Encoder–Decoder Benchmark

Sampling a batch builds the source, its reversal as target, and the shifted decoder input:

V, T = 16, 12   # 16 letters, strings of length 12
BOS = V         # decoder start token

def sample_batch(batch_size, device):
    src = torch.randint(0, V, (batch_size, T), device=device)
    tgt = src.flip(1)
    dec_in = torch.cat([torch.full((batch_size, 1), BOS, device=device),
                        tgt[:, :-1]], 1)
    return src, dec_in, tgt

def to_str(ids):
    return ''.join(chr(ord('a') + int(i)) for i in ids)

src, dec_in, tgt = sample_batch(1, device)
print(f'source {to_str(src[0])!r} -> target {to_str(tgt[0])!r}')
source 'hhkmdnbmelgi' -> target 'iglembndmkhh'

The Decoder Block: Adding a Cross-Attention Sublayer

Decoder Block Anatomy

  • Each DecoderBlock contains three pre-norm residual sublayers on target stream \mathbf{X} \in \mathbb{R}^{B \times T_{\text{dec}} \times d} given encoded source \mathbf{H}_{\text{enc}} \in \mathbb{R}^{B \times T_{\text{src}} \times d}: \mathbf{U} = \mathbf{X} + \mathrm{SelfAttn}_{\mathrm{causal}}(\mathrm{Norm}_1(\mathbf{X})) \mathbf{V} = \mathbf{U} + \mathrm{CrossAttn}(\mathrm{Norm}_2(\mathbf{U}), \mathbf{H}_{\mathrm{enc}}, \mathbf{H}_{\mathrm{enc}}) \mathbf{Y} = \mathbf{V} + \mathrm{FFN}(\mathrm{Norm}_3(\mathbf{V}))

Implementing DecoderBlock in Code

Implementation

Notice that self_attention applies a causal mask over the target prefix, whereas cross_attention attends over the entire encoded source enc (using only an optional source padding cross_mask):

def forward(self, X, enc, mask=None, cross_mask=None):
    if mask is None:                      # Causal mask for target self-attention
        mask = d2l.causal_mask(X.shape[1], device=X.device)
    Y = self.norm1(X)
    X = X + self.self_attention(Y, Y, Y, mask)
    X = X + self.cross_attention(self.norm2(X), enc, enc, cross_mask)
    return X + self.ffn(self.norm3(X))

During autoregressive inference, enc = self.encoder(src) and its cross-attention key–value projections depend only on the source sequence—so they are computed once per prompt and reused at every target decoding step.

Training and Greedy Decoding on String Reversal

End-to-End Seq2Seq

Training a 1-block EncoderDecoder on fresh random batches of 128 strings drives cross-entropy from \ln 16 \approx 2.77\text{ nats} to 0.002\text{ nats} in 300 steps, achieving 100\% exact-string match on 1{,}000 unseen test strings:

loss at step 25/50/100/200/300: 2.077/0.948/0.108/0.004/0.002
exact match on 1000 fresh strings: 1.000
source 'gjapkpfkolmp' -> predicted 'pmlokfpkpajg'

Composing Masks Across the Three Attention Layers

Masking Rules

  • 1. Encoder self-attention (S \times S): Source padding mask (j < s_b).
  • 2. Decoder self-attention (T_{\text{dec}} \times T_{\text{dec}}): Causal lower-triangle \land target padding mask.
  • 3. Cross-attention (T_{\text{dec}} \times S): Source padding mask only—never apply a causal mask to cross-attention, since target token t = 0 must read source token S - 1 immediately.

Pitfall: Do Cross-Attention Weights Show Attribution?

Interpretability Pitfall

  • Without encoder self-attention (without, right heatmap): Encoder slot j holds only token x_j, so cross-attention is forced onto the exact anti-diagonal (t, T-1-t) (100\% of rows).
  • With encoder self-attention (with, left heatmap): Both models achieve 99.9\text{--}100\% reversal accuracy, yet cross-attention aligns with the anti-diagonal on as few as 15\%\text{--}17\% of rows because the encoder’s self-attention layer can already permute or fold tokens across positions.

encoder with self-attention, six runs
  exact match: 1.000 1.000 1.000 1.000 1.000 1.000
  rows on the true source position: 31% 92% 100% 45% 17% 100%
encoder without self-attention, six runs
  exact match: 1.000 1.000 1.000 1.000 1.000 1.000
  rows on the true source position: 100% 100% 100% 100% 100% 100%

Cross-Attention as a Fixed-Size Latent Bottleneck

Perceiver Architecture

  • Decoupling compute from input length N: In CrossAttn, the output sequence length equals the number of queries M, not the number of keys/values N.
  • Perceiver (Jaegle et al., 2021): Uses M \ll N learned latent query vectors \mathbf{Z}_0 \in \mathbb{R}^{M \times d} to cross-attend into an N-token input in O(M N d) time, then runs L self-attention blocks on the short latent array in O(L M^2 d) time—eliminating the O(L N^2 d) bottleneck.
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Implementing PerceiverEncoder in Ten Lines

Latent Bottleneck Code

def forward(self, X):
    Z = self.latents.expand(X.shape[0], -1, -1)
    Z = Z + self.cross_attention(
        self.norm_q(Z), X, X)   # O(M * N) read
    for blk in self.blks:
        Z = blk(Z)              # O(M^2) blocks
    return self.norm(Z)

Choosing Among the Three Wirings in Modern Systems

Architectural Decision Guide

  • Encoder-only: Full 2-sided context in a single parallel pass (embeddings, rerankers, ViT).
  • Decoder-only: Scores 100\% of tokens per pass with one unified stack and KV cache (general LLMs, code, chat).
  • Encoder–decoder: Encodes a long source signal once and decodes compact targets via cross-attention (Whisper speech-to-text, Perceiver resamplers).

Concept Check: Masking, Complexity, and Wiring Choice

Check Your Understanding

Work through these three architectural questions:

  1. Perceiver score count: Suppose an audio or image array has N = 8{,}192 tokens and a PerceiverEncoder uses M = 64 learned latents and L = 6 latent self-attention blocks. Compare the number of attention score pairs per head in the Perceiver against a 6-layer full self-attention encoder.
  2. Cross-attention caching: During autoregressive decoding of T_{\text{dec}} = 100 target tokens from an encoded source of length T_{\text{src}} = 1{,}000, how many times are the cross-attention key and value projections \mathbf{H}_{\text{enc}}\mathbf{W}_k, \mathbf{H}_{\text{enc}}\mathbf{W}_v computed?
  3. Architecture selection: You need to embed 50\text{ million} product descriptions into 768-dimensional vectors for nearest-neighbor search. Which wiring do you choose, and why?

Answers:

  1. Full encoder: 6 \times 8192^2 \approx \mathbf{4.03 \times 10^8} score pairs/head. Perceiver: 64 \times 8192 + 6 \times 64^2 = 524{,}288 + 24{,}576 \approx \mathbf{5.49 \times 10^5} score pairs/head (734\times fewer).
  2. Exactly once (right after the encoder finishes), because \mathbf{H}_{\text{enc}} never changes as target tokens are generated.
  3. Encoder-only: every token benefits from full bidirectional context, and each description is embedded in a single parallel forward pass with no autoregressive decoding loop.

Summary: Encoders, Decoders, and Cross-Attention

Key Takeaways

  • Bidirectional Encoder + MLM: Unmasked self-attention reads full left and right context; replacing 15\% of tokens with <mask> prevents target leakage.
  • Cross-Attention: Bridges separate source and target stacks (\mathbf{Q} from target, \mathbf{K}, \mathbf{V} from \mathbf{H}_{\text{enc}}).
  • Perceiver Latent Bottleneck: M \ll N learned queries reduce attention cost from O(L N^2 d) to O(M N d + L M^2 d).