Masked multi-head self-attention

Query-key dot product

×

The new token's query is compared with every key read from the cache (1,001 positions), in its head.

Si=QiKiT{\htmlData{light=qk-dot}{S_i}}={\htmlData{light=q-head split-heads}{{\htmlClass{vl-stream-q}{Q_i}}}}{\htmlData{light=kv-cache}{{\htmlClass{vl-stream-k}{K_i^{\mathsf T}}}}}
in
QQ [B batch, 12 heads, 1, 64 d_h]KK [B batch, 12 heads, 1001 positions, 64 d_h]
out
SS [B batch, 12 heads, 1 query, 1001 keys]
Sources

In codetf.matmul(q, k, transpose_b=True)

Open pinned code ↗

Direct evidence

The attention kernel forms the per-head query–key matrix before scaling.

model.py 91–94 ↗ · openai/gpt-2 @ 9b63575ef427

Excerpt
    def multihead_attn(q, k, v):

… lines 92–92 omitted …

        w = tf.matmul(q, k, transpose_b=True)
        w = w * tf.rsqrt(tf.cast(v.shape[-1].value, w.dtype))