AI Wiki中文/EN

Encoder–decoder models: read the source, then write the target

编码解码语言模型

Train a three-parameter cross-attention readout and trace the separate source and target information paths.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Read the whole request before answering

A translation model may read an entire source sentence before producing its first target word. That does not violate causality: the source is already available. What it must not read during prediction is the unseen continuation of the target. An encoder–decoder language model keeps these two information paths separate.

The encoder builds representations of the source. The decoder uses its earlier target tokens and those source representations to predict the next target. Their lengths need not match. A short source can produce a long answer, and a long document can produce a short summary. BART uses this arrangement to reconstruct an original document from a corrupted one; T5’s span-corruption task instead predicts the removed spans with sentinel markers. Both are conditional generation tasks, but their target construction differs. BART T5

This chapter adds the source-to-target connection to the separately explained encoder and decoder. Its program trains three scalars in a tiny cross-attention readout. A direct lookup already solves the artificial task, giving us a known target against which to inspect the learned computation.

A three-parameter source reader learns the requested positions while retaining a measurable loss gap.
A three-parameter source reader learns the requested positions while retaining a measurable loss gap.

Three attention paths, two clocks

Let xx be the available source of length SS and yy the target of length TT. A conditional autoregressive model factors the target probability as:

pθ(y∣x)=∏t=1Tpθ(yt∣y<t,x). p_\theta(y\mid x)=\prod_{t=1}^{T}p_\theta(y_t\mid y_{<t},x).

This is a distribution over targets for a given source, not a model of the source probability. The target may include an explicit EOS token. Teacher forcing supplies the correct earlier target tokens during training; the decoder input must be shifted so the current label does not appear as its own input.

Cross-attention takes queries from decoder states and keys and values from encoder states. For query/key width dkd_k:

Q=HdecWQ,K=HencWK,V=HencWV,Z=softmax⁡ ⁣(QK⊤dk+Mcross)V. Q=H_{\mathrm{dec}}W_Q,\quad K=H_{\mathrm{enc}}W_K,\quad V=H_{\mathrm{enc}}W_V, \qquad Z=\operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M_{\mathrm{cross}}\right)V.

The attention matrix is T×ST\times S. It does not require one target position to align with the same source position. Each target query may read every valid source state. Padding is a separate restriction: a padded source key should receive no attention mass. BART, section 2.1

For fully available source text, the three visibility rules are:

Menc(i,j)=0,Mdec(t,u)={0,u≤t,−∞,u>t,Mcross(t,j)=0 M_{\mathrm{enc}}(i,j)=0,\qquad M_{\mathrm{dec}}(t,u)=\begin{cases}0,&u\le t,\\-\infty,&u>t,\end{cases} \qquad M_{\mathrm{cross}}(t,j)=0

on valid positions, with padding additionally blocked. Decoder index tt refers to its shifted input position. A source position with a larger index than tt is not a future target. Applying a lower-triangular mask to the cross-attention matrix just because the decoder is causal would wrongly hide available source evidence. Streaming input needs its own availability rule; the formula here assumes the source has arrived in full. T5, section 3.2.1

Our toy source has two values x0,x1∈{−1,1}x_0,x_1\in\{-1,1\}. The target probabilities correspond to the reversed source: a value plus one asks for probability 0.9, minus one for 0.1. Use a fixed positional template and three trainable scalars, α,w,b\alpha,w,b:

J=(0110),A=softmax⁡row(αJ),ht=∑jAtjxj,zt=wht+b,pt=σ(zt). J=\begin{pmatrix}0&1\\1&0\end{pmatrix},\quad A=\operatorname{softmax}_{\mathrm{row}}(\alpha J),\quad h_t=\sum_j A_{tj}x_j,\quad z_t=wh_t+b,\quad p_t=\sigma(z_t).

Here αJ\alpha J directly parameterizes scaled scores; it is not a learned query/key projection. The encoder is the identity, the two queries are positional, and there is no target self-attention. This is a restricted conditional generator with independent output factors. Those simplifications let us isolate how cross-attention retrieves a requested source position without pretending to train a complete Transformer.

Enumerate all four source pairs. For soft target rit=0.5+0.4xi,1−tr_{it}=0.5+0.4x_{i,1-t}, the binary cross-entropy over eight predictions is:

L=18∑i=14∑t=01[log⁡(1+ezit)−ritzit]. \mathcal L=\frac18\sum_{i=1}^{4}\sum_{t=0}^{1} \left[\log(1+e^{z_{it}})-r_{it}z_{it}\right].

The implementation evaluates the softplus stably with logaddexp. Differentiating row-wise softmax gives the score-scale gradient:

∂L∂α=∑i,tpit−rit8 w∑jxijAtj(Jtj−∑kAtkJtk). \frac{\partial\mathcal L}{\partial\alpha} =\sum_{i,t}\frac{p_{it}-r_{it}}8\,w\sum_j x_{ij}A_{tj} \left(J_{tj}-\sum_k A_{tk}J_{tk}\right).

The other gradients are the sums of (p−r)h/8(p-r)h/8 and (p−r)/8(p-r)/8 for ww and bb. A constant prediction 0.5 has loss log⁡2\log2. If attention selects the reversed position exactly, w=log⁡9,b=0w=\log9,b=0 achieves the known entropy floor −0.9log⁡0.9−0.1log⁡0.1-0.9\log0.9-0.1\log0.1. Finite scores leave some mixing, so finite training need not attain that floor exactly.

Train the reader and inspect what it reads

The original NumPy program optimizes the three parameters for 1,200 gradient steps. It reports the attention matrix, probabilities and loss history. It also swaps source positions after training to test that the output actually depends on the source arrangement.

"""Original cross-attention readout, not a complete Transformer or T5."""
import itertools
import json
import numpy as np


def dataset():
    source = 2 * np.array(list(itertools.product([0., 1.], repeat=2))) - 1
    target = .5 + .4 * source[:, ::-1]
    return source, target


def forward(theta, source):
    theta, source = np.asarray(theta, float), np.asarray(source, float)
    if theta.shape != (3,) or source.ndim != 2 or source.shape[1] != 2:
        raise ValueError('Three parameters and two source positions required')
    if not np.isfinite(theta).all() or not np.isfinite(source).all():
        raise ValueError('Finite inputs required')
    alpha, weight, bias = theta
    template = np.array([[0., 1.], [1., 0.]])
    scores = alpha * template
    a = np.exp(scores - scores.max(axis=1, keepdims=True))
    a /= a.sum(axis=1, keepdims=True)
    h = source @ a.T
    z = weight * h + bias
    p = np.exp(-np.logaddexp(0, -z))
    return p, z, h, a


def objective(theta, source, target):
    target = np.asarray(target, float)
    p, z, h, a = forward(theta, source)
    if target.shape != p.shape or not np.isfinite(target).all() or ((target < 0) | (target > 1)).any():
        raise ValueError('Targets must be probabilities matching the outputs')
    loss = np.mean(np.logaddexp(0, z) - target*z)
    dz = (p-target)/p.size
    template = np.array([[0., 1.], [1., 0.]])
    da = a * (template - (a*template).sum(axis=1, keepdims=True))
    grad = np.array([np.sum(dz*theta[1]*(source@da.T)), np.sum(dz*h), np.sum(dz)])
    return float(loss), grad


def demo():
    x, y = dataset()
    theta = np.array([.5, .5, 0.])
    trace = []
    for step in range(1201):
        loss, grad = objective(theta, x, y)
        if step % 200 == 0:
            trace.append([step, loss])
        if step < 1200:
            theta -= .5*grad
    p, _, _, a = forward(theta, x)
    # Source permutation changes the requested positional task.
    swapped = forward(theta, x[:, ::-1])[0]
    return dict(parameters=theta.tolist(), attention=a.tolist(), probabilities=p.tolist(),
                trace=trace, constant_baseline=float(np.log(2)),
                entropy_floor=float(-.9*np.log(.9)-.1*np.log(.1)),
                source_change=float(np.max(abs(p-swapped))),
                target_permutation=[1, 0], scope='Identity encoder; position-only queries; three trained scalars; independent output factors')


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2))

The final attention gives about 0.958157 probability to the requested opposite position and 0.041843 to the other. Final loss is about 0.325497, above the entropy floor 0.325083 and below the constant baseline 0.693147. The difference from the floor is retained rather than rounded away. Swapping source positions changes an output probability by about 0.782132.

The accompanying tests compare all three analytic gradients with centered finite differences. They check uniform attention at zero score scale, the hard-selection limit, normalization over all four binary output strings, source dependence and invalid input rejection. These checks establish the toy’s computation. They do not measure translation, summarization or language understanding.

For full dense attention, the score/value work per layer scales approximately with (S2+T2+ST)d(S^2+T^2+ST)d, plus projection and feed-forward costs involving d2d^2. This expression distinguishes the encoder, decoder and cross-attention terms; it is not a wall-clock estimate. During autoregressive decoding, a fixed source allows encoder states and projected source keys/values to be reused. That optimization is separate from the decoder’s growing target KV cache.

Source access does not guarantee source faithfulness

The availability of source states says what the model can read, not what it must use. A trained decoder can rely too heavily on target-side regularities, or it can attend to a source without faithfully reproducing its content. Our source-swap test catches complete source independence in this toy; it cannot establish factual grounding in an open-ended model.

The example also knows which source position each query should seek through the fixed template JJ. A realistic model must learn representations and useful retrieval patterns. Here a two-entry lookup is an exact, cheaper baseline. The point of training is to inspect a soft retrieval mechanism and its gradients, not to claim attention is necessary for reversal.

A single-stack prefix language model can also let an input prefix use bidirectional attention while keeping target prediction causal. T5’s architectural comparison distinguishes that arrangement from separate encoder and decoder stacks. Counting stacks, parameter sharing and attention visibility matters more than calling every conditional model “seq2seq.” T5, section 3.2.1

Follow the information

  1. The source has ten tokens and the target is at its first prediction. May cross-attention read the tenth source token?

Answer: Yes, if the entire source is available and that token is valid. Target causality blocks future target information, not already available source positions. A streaming-source task would need a different availability mask.

  1. Set α=0\alpha=0 and use source values (−1,1)(-1,1). Can this toy distinguish the two requested positions?

Answer: No. Both attention rows become (0.5,0.5), giving both hidden values zero. A shared scalar readout then returns the same probability at both positions, even though the desired targets differ.

  1. Why is the correct target loss above zero even with perfect retrieval?

Answer: The targets are probabilities 0.1 and 0.9, not deterministic labels. Their conditional entropy is about 0.325083 nats. Perfectly matching those probabilities reaches the entropy floor; it does not eliminate the uncertainty built into the task.

  1. If only the source changes during generation, can old cross-attention keys and values always be reused?

Answer: No. They were computed from the previous source and become stale. Reuse requires the same source, encoder computation, projection parameters and positional conventions; target-side cache validity is an additional issue.

Compare the input and the reconstruction target

BART’s denoising setup is useful for seeing why corrupted source length need not equal target length. T5’s comparison is useful for distinguishing encoder–decoder, ordinary language-model and prefix language-model visibility. The two papers also show why “denoising” alone does not specify which target sequence is predicted. BART T5

A follow-up experiment can remove the positional template and train query/key projections on a held-out set of source combinations. Compare with the direct lookup, report the source-swap effect and the excess loss above the known conditional entropy, and inspect whether results survive longer sources. Such extensions test the limits of the teaching example instead of turning its four input pairs into a language benchmark.

Make a prediction, then check

Where can a decoder cross-attention query look?

Choose one answer

Learning objectives

  • Train a three-parameter cross-attention readout and trace the separate source and target information paths.
  • Explain why full source visibility is compatible with causal target prediction.
  • Separate encoder reuse from target KV caching and recognize when changing the source invalidates a cache.

Prerequisites & connections

Explore related knowledge →

References

  1. Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer
    Colin Raffel; Noam Shazeer; Adam Roberts; Katherine Lee; Sharan Narang; Michael Matena; Yanqi Zhou; Wei Li; Peter J. Liu · 2020
  2. BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension
    Mike Lewis; Yinhan Liu; Naman Goyal; Marjan Ghazvininejad; Abdelrahman Mohamed; Omer Levy; Ves Stoyanov; Luke Zettlemoyer · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked BART2.1 and T5 architecture comparison3.2.1, including source/target visibility. Six paired equations and four explained exercises; three-parameter cross-attention readout, all gradient finite differences, conditional normalization and source swaps. Identity encoder and fixed positional retrieval template; direct lookup already solves the task, not a full Transformer.

  • Single AI author checked BART2.1 and T5 architecture comparison3.2.1, including source/target visibility. Six paired equations and four explained exercises; three-parameter cross-attention readout, all gradient finite differences, conditional normalization and source swaps. Identity encoder and fixed positional retrieval template; direct lookup already solves the task, not a full Transformer.
  • Four computed SVG variants per topic. Fifteen numeric/geometry tests and42 responsive cases passed; fourteen final Chinese-mobile/English-desktop screenshots actually inspected. Initial English mobile-heading clipping and corrections preserved. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.