Skip to content

← Attention & Transformers step 4 of 8

Medium Research

Cross Attention

Cross-attention lets one sequence read information from another. Each query compares itself with every key, then uses those scores to take a weighted average of the values. For example, a translation decoder can use its own queries to read an encoder's representation of the source sentence.

The calculation is the same as scaled dot-product attention. What makes it cross-attention is where the queries and key/value pairs come from.

Your task

Implement cross_attention(Q, K, V) for these floating-point arrays:

  • Q: shape (tgt_len, d_k), one row per query.
  • K: shape (src_len, d_k), one row per source key.
  • V: shape (src_len, d_k), one value vector per source key.

The lengths and d_k are positive. The two sequence lengths can differ; K and V must have the same number of rows. This exercise uses the same feature width for queries, keys and values.

Compute scores = Q @ K.T / sqrt(d_k), with shape (tgt_len, src_len). Apply softmax across each row, over the source positions, then multiply those weights by V. Return shape (tgt_len, d_k), one value mixture per query. Use a numerically stable softmax.

There is no mask, dropout, batch dimension or learned projection in this exercise. Every query can attend to every source position.

Example

A zero query gives every key the same score. With values [[2, 0], [0, 4]], its output is their average, [[1, 2]]. A nonzero query can give the two values different weights.

The comparison below shows allowed connections, not their weights. The cross-attention panel illustrates why the score matrix can be rectangular.

Loading visualization…