Queries From One Side

TransformersMedium+20 XP+20

Queries From One Side

The encoder has read the French sentence and produced one vector per input word. The decoder is part-way through writing the English, with its own vector for each output position so far. Cross-attention is the only wire between the two stacks, and it is ordinary attention with one change: the query comes from the decoder, the keys and the values from the encoder.

Task: write cross_attention(decoder_states, encoder_outputs, Wq, Wk, Wv), returning one context vector per decoder position, rounded to 4 decimal places.

argumentshapewhat it is
decoder_statesTTT vectors of length dddone per output position, written DDD below
encoder_outputsSSS vectors of length dddone per input word, written EEE below
Wqd×dkd \times d_kd×dk​projects a decoder state into a query
Wkd×dkd \times d_kd×dk​projects an encoder output into a key
Wvd×dvd \times d_vd×dv​projects an encoder output into a value

Project, score, scale, softmax, blend:

Q=DWq,K=EWk,V=EWvQ = D W_q, \qquad K = E W_k, \qquad V = E W_vQ=DWq​,K=EWk​,V=EWv​

scorets=Qt⋅Ksdk\text{score}_{ts} = \frac{Q_t \cdot K_s}{\sqrt{d_k}}scorets​=dk​​Qt​⋅Ks​​

Softmax each decoder row across all SSS encoder positions, giving weights wtsw_{ts}wts​ that sum to 111 for each ttt, then

contextt=∑s=1Swts Vs\text{context}_t = \sum_{s=1}^{S} w_{ts}\, V_scontextt​=∑s=1S​wts​Vs​

Return the TTT context vectors, each of length dvd_vdv​. There is no mask anywhere in this operation: the encoder has already read the entire input, so every output position is free to draw on all of it.

Nothing here is a new mechanism. Point all three projections at a single sequence instead of two and this identical code is self-attention — which is why one block can serve translation, classification and generation alike.

Examples

decoder_states = [[1.0, 0.0], [1.0, 1.0]]
encoder_outputs = [[2.0, 0.0], [0.0, 2.0]]
Wq = [[1.0, 0.0], [0.0, 1.0]]
Wk = [[0.0, 1.0], [1.0, 0.0]]
Wv = [[1.0, 1.0], [1.0, -1.0]]
returns [[2.0, -1.2177], [2.0, 0.0]]
decoder_states = [[1.0, 0.0, -1.0], [0.5, 1.0, 1.0], [2.0, -1.0, 1.0]]
encoder_outputs = [[1.0, 2.0, 0.0], [0.0, -1.0, 3.0]]
Wq = [[1.0, 0.0], [0.5, 1.0], [0.0, -1.0]]
Wk = [[0.0, 1.0], [1.0, 0.0], [1.0, 1.0]]
Wv = [[1.0, 0.0, 0.5], [0.0, 1.0, 0.0], [0.5, 0.0, 1.0]]
returns [[1.4022, -0.4133, 2.5111], [1.25, 0.5, 1.75], [1.0279, 1.8326, 0.6395]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run