Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

4.3 Encoder-Decoder (T5/BART)

An editor wants to shorten the caption a red fox to red fox. When the model produces its first word, can it already read fox? Yes, on the source side. On the target side, it has only the start token. An encoder-decoder Transformer keeps these two sequences separate. The encoder reads the source once. At each output step, the decoder reads the target prefix and uses cross-attention to consult the encoder’s representations. [4]

Reading the source while writing the target

Treat each word as one token for this example. The batch has four source slots, a red fox PAD. During training, the two decoder inputs are START red and their labels are red fox. START stands for the model’s decoder-start token. We stop after the second word. An end-of-sequence prediction would need one more row.

The original Transformer applies self-attention and then a feed-forward network within each encoder block. Within each decoder block, it applies causal self-attention, cross-attention to the final encoder states, then a feed-forward network. The tables show which keys a query can read at each kind of attention. [4]

Rows are queries and columns are keys. A 1 allows access. A 0 blocks it.

Encoder self-attention
Query aredfoxPAD
a 1110
red 1110
fox 1110
Decoder self-attention
Query STARTred
START 10
red 11
Cross-attention
Query aredfoxPAD
START 1110
red 1110
Tables calculated for this example from the original Transformer’s attention rules. The unused encoder PAD query row is omitted. [4]

Read the START row twice. Its decoder self-attention can see only START, so it cannot copy the target label red. Its cross-attention can read all three source words, including the source word red. The source caption will also be present at inference. The next decoder row can read both START and the supplied target word red to predict fox. At inference the decoder feeds back its generated word. For the one-sequence versions of these rules, see the encoder mask in §4.1 and the shifted labels in §4.2.

Why the cross-attention scores have two rows and four columns

In one decoder block, take queries QQ from its target states after causal self-attention. Project keys KK and values VV from the final encoder states. For one head of key dimension dkd_k, the rows of the result are weighted sums of source values. [4]

A=softmax⁡source ⁣(QKT/dk+M),O=AV.A=\operatorname{softmax}_{\text{source}}\!\left(QK^{\mathsf T}/\sqrt{d_k}+M\right),\qquad O=AV.

Here MM adds zero to a valid source score and −∞-\infty to a padding score. For TT target input positions and SS padded source slots, both AA and the broadcast mask have effective shape T×ST\times S per head. In the example T=2T=2, S=4S=4. Each row sums to one over the three valid source slots. Two rows with the same visibility can assign very different weights.

Test the padding mask by changing one value

The CPU example below starts at the projected queries, keys and values. It uses one batch item, one head, one feature and at least one valid source key. It omits learned projections, residual connections, dropout, batching across examples and the training loop. PyTorch’s scaled dot-product attention accepts a Boolean mask in which True allows a key. A single source-mask row broadcasts over both decoder queries. [5]

Download the PyTorch example (cross_attention.py)

"""Two decoder queries over three source tokens and one pad. Requires PyTorch.

Foundation Model Engineering, section 4.3
English: https://sungeuns.github.io/foundation-model-engineering/chapter-4/encoder-decoder/#cross-attention-example
Korean: https://sungeuns.github.io/foundation-model-engineering/ko/chapter-4/encoder-decoder/#cross-attention-example
"""

import math

import torch
from torch.nn.functional import scaled_dot_product_attention


def cross_attention(values, mask):
    # Each input has shape (batch=1, heads=1, positions, head_dim=1).
    query = torch.tensor([0.0, math.log(2)]).reshape(1, 1, 2, 1)
    key = torch.tensor([0.0, 1.0, 2.0, 3.0]).reshape(1, 1, 4, 1)
    value = torch.tensor(values).reshape(1, 1, 4, 1)
    return scaled_dot_product_attention(query, key, value, attn_mask=mask).flatten()


if __name__ == "__main__":
    source_mask = torch.tensor([[True, True, True, False]])
    baseline = cross_attention([3.0, 6.0, 12.0, 90.0], source_mask)
    pad_changed = cross_attention([3.0, 6.0, 12.0, 900.0], source_mask)
    fox_changed = cross_attention([3.0, 6.0, 33.0, 90.0], source_mask)
    torch.testing.assert_close(baseline, torch.tensor([7.0, 9.0]))
    torch.testing.assert_close(pad_changed, baseline)
    torch.testing.assert_close(fox_changed - baseline, torch.tensor([7.0, 12.0]))
    print("baseline:", baseline.tolist())
    print("change from raising fox by 21:", (fox_changed - baseline).tolist())

Run python cross_attention.py. The first query is zero, so its three valid keys have equal weight and return (3+6+12)/3=7(3+6+12)/3=7. For the second query the three unnormalized weights are 1,2,41,2,4, so it returns (3+12+48)/7=9(3+12+48)/7=9. Changing the padding value from 90 to 900 leaves both outputs unchanged. Raising the source value for fox by 21 adds 7 to the first output and 12 to the second. A triangular cross-attention mask would incorrectly hide fox from the first query and fail this test.

What should the decoder reconstruct in T5 and BART?

Take the sentence the red fox crossed the bridge and hide red fox. Both models can put the damaged sentence in the encoder. Write down the target labels before choosing your loss. These are illustrative word-level strings, with tokenizer-specific start and end IDs omitted.

Training objectiveEncoder inputDecoder target
T5 span corruptionthe <X> crossed the bridge<X> red fox <Y>
BART text infillingthe <mask> crossed the bridgethe red fox crossed the bridge

In the T5 paper’s example format, each missing span gets a distinct sentinel, and a final sentinel closes the target. The decoder predicts the missing spans and their delimiters. The same text-to-text interface can later emit a class label such as positive. Raffel et al. used the C4 corpus for pre-training. [1]

BART reconstructs the entire original sequence, including unchanged words. Lewis et al. tested several ways to damage a document. Their large model combined span infilling with sentence permutation. If a data pipeline gives both models the full original sentence as labels, it has silently changed the T5 objective. [2]

A causal encoder changes the visibility rule

Research snapshot as of 2026-11-25. DeepSeek’s V4.1-Flash report describes a causal encoder-decoder (CED). For global attention, the lower half of the stack is a causal encoder. Upper layers derive global cache entries from the midpoint states through layer-specific projections. The report distinguishes work during prompt prefill and token decoding. A later prompt token therefore cannot change an earlier causal encoder state. In the T5/BART-style source encoder above, an earlier source word can read a later one. The distinction matters when deciding which representations can be reused as a prompt grows. [3] Chapter 4.5

Quizzes

Quiz 1: Why can the first target row read the source word “red” while predicting the target word “red”? The source is available at inference. On the target side, only the start token is visible in that row. Feeding the target label itself into the first decoder row would leak the answer.

Quiz 2: Why does a batch with two target inputs and four source slots need a rectangular cross-attention mask? Each query belongs to a target input and each key belongs to a source slot. Both target queries may read all three real source words. A target-side triangular mask would wrongly hide later source words.

Quiz 3: A padding-value change leaves the output unchanged. Why also change a real source value? A broken computation that ignores every source value could also pass the padding test. In this fixture changing the final real value shifts both outputs by known, different amounts.

Quiz 4: After hiding “red fox,” which model has a training label for the unchanged word “crossed”? BART reconstructs the full original sentence. The T5 span-corruption target contains only the hidden span and its sentinel delimiters.

Quiz 5: Can the first source state from a T5-style encoder be reused unchanged after extending its source? It can attend to the new source token, so extending the source can change that state. A strictly causal encoder keeps its earlier positions independent of appended tokens.

References

  1. Raffel, C., et al. (2020). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. Paper, Figure 2.
  2. Lewis, M., et al. (2020). BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension. ACL Anthology.
  3. DeepSeek-AI. (2026). DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression. Technical report.
  4. Vaswani, A., et al. (2017). Attention Is All You Need. Paper, §3.
  5. PyTorch. Scaled dot-product attention, PyTorch 2.15.