Skip to the content

fatehi.devx2Learning

Deep learning

Multi-head attention

Several attentions side by side, each with its own queries, keys and values, their outputs joined and mixed by one matrix.

Before this

One reading is not enough

One attention gives each position one set of weights: one way of deciding what matters. But a word has many relations at once: “sat” needs its subject, its place and its tense. Multi-head attention runs several attentions, the heads, side by side, each with its own query, key and value matrices, so each can learn to look for something different.

MultiHead(X)=Concat(head1,…,headh)WO,headi=Attention(XWiQ,XWiK,XWiV)

Head i has its own matrices WiQ, WiK and WiV, each of shape (d, d/h), and gives one vector of length d/h per position. The h heads’ vectors are joined end to end (concat) into one of length d, and one matrix WO of shape (d, d) mixes them.

Multi-head attention: each head with its own Q, K and V and its own weights (the stack behind the first), all at once; their outputs joined (concat) and mixed by one matrix, WO.

The same cost as one wide head

Each head works on vectors h times narrower, so h heads cost about as much as one attention of full width. In code the h query matrices are usually stored side by side as one (d, d) matrix and the result cut into h pieces; that is the same thing as separate matrices, computed in one product. After training, different heads are often found to do recognisably different jobs, such as following the previous word or linking a pronoun to its noun, but nothing forces them to.

Test yourself

  1. Do the heads share their query, key and value matrices?

    No: each head has its own. Code often stores them side by side in one matrix and computes them in one product, but each head uses its own slice.

  2. What does WO do, and how many are there in one layer?

    One per layer: it mixes the heads’ outputs, joined end to end, back into one vector of the model’s width.

  3. Why do eight heads cost about as much as one?

    Each works on vectors eight times narrower (64 instead of 512), so the eight together do about the same amount of arithmetic as one head of full width.

Where it leads

Kept in this browser only, never sent.

Paths through it