#122Cross-Attention (Encoder-Decoder)MediumTransformersAsked atOpenAI · Google · Anthropic
Cross-Attention (Encoder-Decoder)
Background
Self-attention queries within one sequence; cross-attention lets the decoder attend over the encoder's outputs. It's the transformer's encoder-decoder bridge — used in machine translation, image-conditioned text generation, and most multimodal architectures.
Problem statement
Implement cross_attention(Q, K, V) returning:
where comes from the decoder and from the encoder. Use numerically stable row-wise softmax.
Input
Q—np.ndarrayshape , decoder queries.K—np.ndarrayshape , encoder keys.V—np.ndarrayshape , encoder values. Note: and share their first dimension.
Output
Returns np.ndarray shape .
Examples
Example 1 — basic shape
Input: Q shape=(3, 4), K shape=(5, 4), V shape=(5, 6)
Output: shape=(3, 6)
Example 2 — hard attention via large logits → output equals one row of V
Input: Q designed to overwhelmingly favour K[0]
Output: ≈ V[0]
Example 3 — uniform Q over K → output is the mean of V
Input: Q=0 (uniform softmax)
Output: row-wise mean of V
Constraints
Q.shape[-1] == K.shape[-1](shared ).K.shape[0] == V.shape[0](same ).- Softmax must subtract the row max before
expfor stability.
Notes
- No masking here. Decoder self-attention typically masks future tokens; cross-attention does not (the decoder can attend over the full encoder output).
- Multi-head. Production transformers split into heads, apply attention per head, concatenate. This problem isolates one head.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Example: hard attention to K[0] returns V[0]
- •Reference: uniform Q gives mean of V
- •Sample: output shape (T_q, d_v)