Skip to the content

fatehi.devx2Learning

Deep learning

Cross-attention

Attention whose queries come from one sequence and whose keys and values come from another: how a decoder reads what the encoder made.

Before this

Reading another sequence

In self-attention a sequence reads itself. In cross-attention it reads another one: the queries come from the sequence being built, the keys and values from a second sequence that has already been read. It is how an encoder-decoder network brings the input into the output: while the decoder writes a word, its query asks which of the encoder’s vectors matter now.

CrossAttention(Y,X)=softmax((YWQ)(XWK)Tdk)XWV

Y holds the decoder’s vectors (m of them), X the encoder’s (n). The table of scores is m × n: one row for each word being written, one column for each word of the input. Nothing is masked: the whole input is known.

The decoder writing the German sentence; each new word’s query reads the English words’ keys and values, and its row of weights is brightest at the word it translates.

The weights of cross-attention are often readable: drawn as a table of output words against input words, they trace which source words each target word leaned on, an alignment, learned from translations alone. Cross-attention is the descendant of Bahdanau’s attention of 2014, which had a recurrent decoder read the states of a recurrent encoder in the same way.

Test yourself

  1. In the decoder’s cross-attention, where do the queries come from, and where the keys and values?

    The queries from the decoder’s own vectors; the keys and values from the encoder’s output.

  2. Why is cross-attention not masked like the decoder’s self-attention?

    Its keys and values are the input sentence, which is known whole before writing starts; only the output’s future words must be hidden.

  3. Which encoder layer do the decoder’s six cross-attentions read?

    All read the output of the encoder’s last layer.

Where it leads

Kept in this browser only, never sent.

Paths through it