Attention⁡(Q,K,V)\operatorname{Attention}(Q,K,V)

Scaled dot-product attention

Each token scores every other token, turns the scores into weights that add up to 1, and takes the weighted average of their value vectors.

Attention⁡(Q,K,V)=Softmax⁡ ⁣(QK⊤dk+M)V\operatorname{Attention}(Q,K,V) = \operatorname{Softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V

Read it step by step, with NN tokens:

  1. QK⊤QK^\top is an N×NN \times N table: how well each token's query matches each token's key. (In cross-attention the keys come from a different sequence of length MM, and the table is N×MN \times M.)
  2. Divide by dk\sqrt{d_k} so the scores stay in a range where softmax still responds to differences.
  3. Add the mask MM to block positions a token must not see.
  4. Softmax each row, so each token's weights add up to 1.
  5. Multiply by VV: each token gets a weighted blend of the value vectors.

Where the course uses it

Related terms