Cross-Attention Reads Encoder Records

Cross-attention projects decoder records into queries and encoder records into keys and values. Derive the target-by-source score shape, calculate a small matrix, and audit source assignment and masking.

Cross-attention assigns projected decoder records to queries and projected encoder records to keys and values. The source distinction is the operation's defining contract.

Let decoder state D:(B,Tt,dmodel)D:(B,T_t,d_{model}) and encoder state H:(B,Ts,dmodel)H:(B,T_s,d_{model}). For one head,

Q=DWQ:(B,Tt,dk),Q=DW_Q:(B,T_t,d_k), K=HWK:(B,Ts,dk),V=HWV:(B,Ts,dv).K=HW_K:(B,T_s,d_k),\qquad V=HW_V:(B,T_s,d_v).

Therefore

S=QKdk:(B,Tt,Ts),S=\frac{QK^\top}{\sqrt{d_k}}:(B,T_t,T_s),

and the weighted source reading has shape (B,Tt,dv)(B,T_t,d_v) before the head outputs are combined and projected.

Trace Two Target Queries and Three Source Records

For Tt=2T_t=2, Ts=3T_s=3, and one-dimensional queries and keys, choose

Q=[12],K=[101].Q=\begin{bmatrix}1\\2\end{bmatrix},\qquad K=\begin{bmatrix}1\\0\\-1\end{bmatrix}.

With dk=1d_k=1, the score matrix is

S=QK=[101202].S=QK^\top= \begin{bmatrix} 1&0&-1\\ 2&0&-2 \end{bmatrix}.

Each target row softmaxes across three source columns. The second distribution is sharper because its score differences are larger.

If source values are V=[10,20,30]V=[10,20,30]^\top, each target output is a weighted sum of these three values. There is no target-value column in this cross-attention operation.

Source Padding and Causality Are Different

Cross-attention normally masks padded or unavailable source columns. It does not usually need the target-side triangular mask because every current target query may read the complete available source. Causality is already enforced in target self-attention and target shifting.

A Source-Swap Audit

Hold decoder state fixed and alter one encoder record. Cross-attention outputs may change. Hold encoder state fixed and alter one later target record: an earlier target query must remain unchanged through causal decoder computation. Together these interventions test source assignment and target leakage.

Q1. Derive a cross-attention shape

For B=4B=4, Tt=5T_t=5, and Ts=7T_s=7, what is the per-head cross-attention score shape?

Answer it first, then check.

Hint
Use (B,Tt,Ts)(B,T_t,T_s).
Solution
The score shape is (4,5,7)(4,5,7).
Not attempted
Review

Not marked done.

Pause and reflect

In your own words, note what you understood, what remains unclear, or what you want to revisit. The note stays with this lesson.

0 of 1 exercises marked done

Review

Not marked done.